Android: how to handle a button

Having a solid background in the non-Java and non-Android fields, I am learning Android.

I have a lot of confusion with different areas, one of them is the handling of button clicks. There are at least 4 ways to do this (!!!), they are briefly listed here.

for the purpose of harmonization I have listed them:

  • Have a member of the View.OnClickListener class in action and assign it to an instance that will handle the onClick logic in the onClick activity onCreate .

  • Create an 'onClickListener' in the onCreate activity method and assign it to the button using setOnClickListener

  • Deploy 'onClickListener' in the action itself and assign 'this' as the listener for the button. For the case when an activity has several buttons, the button identifier must be analyzed to execute the onClick handler for the correct button

  • Have a public activity method that implements the onClick logic and assigns it to a button in an xml activity declaration.

Question number 1:

Are there all these methods, is there another option? (I do not need others, just curious)

For me, the most intuitive way would be the most recent: it requires the least amount of code and is the most readable (at least for me).

Although, I do not see this approach widely used. What are the downsides to using it?

Question number 2:

What are the pros and cons for each of these methods? Share your experience or a good link.

Any feedback is appreciated!

PS I tried to find Google and find something for this topic, but the only thing I found was a description of how to do it, and not why it is good or bad.

+62
java android android-button onclicklistener
Feb 08 '13 at 23:15
source share
8 answers

Question 1: Unfortunately, the one you are talking about is the most intuitive, least used on Android. As far as I understand, you should separate your user interface (XML) and computational functionality (Java class files). It also simplifies debugging. It is actually much easier to read this way and think about Android imo.

Question 2: I believe that two and # 3 are mainly used. As an example, I use ButtonButton.

2

is in the form of an anonymous class.

 Button clickButton = (Button) findViewById(R.id.clickButton); clickButton.setOnClickListener( new OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub ***Do what you want with the click here*** } }); 

This is my favorite as it has an onClick method next to where the button variable was set using findViewById. It seems very neat and tidy that everything related to this ButtonButton mouse click is here.

The con my colleague comments on is that you imagine you have a lot of views that need an onclick listener. You can see that your onCreate will be very long. Therefore, he likes to use:

3

Say what you have, 5 clicks:

Make sure your Activity / Fragment implements OnClickListener

 // in OnCreate Button mClickButton1 = (Button)findViewById(R.id.clickButton1); mClickButton1.setOnClickListener(this); Button mClickButton2 = (Button)findViewById(R.id.clickButton2); mClickButton2.setOnClickListener(this); Button mClickButton3 = (Button)findViewById(R.id.clickButton3); mClickButton3.setOnClickListener(this); Button mClickButton4 = (Button)findViewById(R.id.clickButton4); mClickButton4.setOnClickListener(this); Button mClickButton5 = (Button)findViewById(R.id.clickButton5); mClickButton5.setOnClickListener(this); // somewhere else in your code public void onClick(View v) { switch (v.getId()) { case R.id.clickButton1: { // do something for button 1 click break; } case R.id.clickButton2: { // do something for button 2 click break; } //.... etc } } 

Thus, as my colleague explains, it is accurate in the eyes, since all onClick calculations are processed in one place and do not overwhelm the onCreate method. But the drawback that I see is that:

  • looking at themselves
  • and any other object that can be located in onCreate used by the onClick method must be made in the field.

Let me know if you want more information. I did not fully answer your question, because it is a rather long question. And if I find several sites, I will expand my answer, right now I'm just giving some experience.

+101
Feb 08 '13 at 23:44
source share

# 1 I often use the latter when there are buttons on the layout that are not generated (but obviously static).

If you use it in practice and in a business application, pay special attention here, because when you use an obfuscater source , such as ProGuard, you need to note these methods in your activity so that they are not confused.

To archive a system at compile time with this approach, see Android Lint ( example ).




# 2 Pros and cons for all methods are almost the same, and the lesson should be:

Use what ever is most suitable or feels the most intuitive for you.

If you need to assign the same OnClickListener to multiple button instances, save them in the class area (# 1). If you need a simple button listener, do an anonymous implementation:

 button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { // Take action. } }); 

I try not to implement OnClickListener in activity, this is a little confused from time to time (especially when you implement several other event handlers, and no one knows what this does).

+9
Feb 08 '13 at 23:29
source share

The most used method is an anonymous declaration

  Button send = (Button) findViewById(R.id.buttonSend); send.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // handle click } }); 

You can also create a View.OnClickListener object and set it to the button later, but you still need to override the onClick method, for example

 View.OnClickListener listener = new View.OnClickListener(){ @Override public void onClick(View v) { // handle click } } Button send = (Button) findViewById(R.id.buttonSend); send.setOnClickListener(listener); 

When your activity implements the OnClickListener interface, you must override the onClick (View v) method at the activity level. Then you can check this activity as a listen button on the button, since it already implements the interface and overrides the onClick () method

 public class MyActivity extends Activity implements View.OnClickListener{ @Override public void onClick(View v) { // handle click } @Override public void onCreate(Bundle b) { Button send = (Button) findViewById(R.id.buttonSend); send.setOnClickListener(this); } } 

(imho) The 4th approach is used when several buttons have the same handler, and you can declare one method in the activity class and assign this method to several buttons in the xml layout, you can also create one method for one button, but in in this case, I prefer to declare handlers inside the activity class.

+4
Feb 08 '13 at 23:32
source share

I prefer option 4, but it makes intuitive sense to me because I work too much in Grails, Groovy and JavaFX. The "magic" connections between the view and the controller are common. It is important to name this method well:

In the view, add the onClick method to the button or other widget:

  android:clickable="true" android:onClick="onButtonClickCancel" 

Then in the class, process the method:

 public void onButtonClickCancel(View view) { Toast.makeText(this, "Cancel pressed", Toast.LENGTH_LONG).show(); } 

Again, name the method clearly, something that you should do anyway, and maintenance becomes secondary.

One big advantage is that you can now write unit tests for this method. Option 1 can do this, but 2 and 3 are harder.

+4
Dec 19 '15 at 17:44
source share

Options 1 and 2 involve using an inner class that will create mess type code. Option 2 is pretty dirty because there will be one listener for each button. If you have a small number of buttons, everything is in order. For option 4, I think it will be harder to debug, since you will have to return both the fourth xml and java code. I personally use option 3 when I have to handle a few keystrokes.

+1
Feb 08 '13 at 23:29
source share

My sample tested in Android 2.1 studio

Define button in xml layout

 <Button android:id="@+id/btn1" android:layout_width="wrap_content" android:layout_height="wrap_content" /> 

Java ripple phenomenon

 Button clickButton = (Button) findViewById(R.id.btn1); if (clickButton != null) { clickButton.setOnClickListener( new View.OnClickListener() { @Override public void onClick(View v) { /***Do what you want with the click here***/ } }); } 
+1
Aug 03 '16 at 16:39
source share

Question # 1 is the only way to handle clicks on a view.

Question No. 2 -
Option # 1 / Option # 4 - There is not much difference between option # 1 and option # 4. The only difference that I see in one case is to implement OnClickListener, while in another case there will be an anonymous implementation.

Option # 2 - An anonymous class will be created in this method. This method is a bit cumborsome, since you will need to do this several times if you have several buttons. For anonymous classes, you should be careful when handling memory leaks.

Option number 3 - Although, this is an easy way. Typically, programmers try not to use any method until they write it, and therefore this method is not widely used. You will see that most people use option number 4. Because it is cleaner in terms of code.

0
Feb 08 '13 at 23:29
source share

Step 1: Creata XML File

 <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical"> <Button android:id="@+id/btnClickEvent" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Click Me" /> </LinearLayout> 

Step 2: Create MainActivity

 package com.scancode.acutesoft.telephonymanagerapp; import android.app.Activity; import android.os.Bundle; import android.view.View; import android.widget.Button; public class MainActivity extends Activity implements View.OnClickListener { Button btnClickEvent; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); btnClickEvent = (Button) findViewById(R.id.btnClickEvent); btnClickEvent.setOnClickListener(MainActivity.this); } @Override public void onClick(View v) { //Your Logic } } 

Happycode

0
Apr 18 '16 at 10:44
source share



All Articles