Android Button setOnClickListener Design

AndroidButtonDesign PatternsOnclicklistener

Android Problem Overview


I am building an Android Application. I've noticed that I am creating many repetitions of code similar to this in each of my classes:

Button buttonX = (Button)findViewById(R.id.buttonXName);
// Register the onClick listener with the implementation above
buttonX.setOnClickListener(new OnClickListener() {
	public void onClick(View v)
	{
		//DO SOMETHING! {RUN SOME FUNCTION ... DO CHECKS... ETC}
	} 
});

I now have fifteen buttons and this is making my code ugly. Does anyone have a class or some examples on how I can turn all these codes into something more efficient, so I can:

  1. Create the button object {Button buttonX (Button)findViewById(R.id.buttonXName);}
  2. Set the listener {buttonX.setOnClickListener(new OnClickListener()}
  3. Determine if it was clicked {public void onClick(View v)}
  4. Then run specific code for each button?

If anyone knows anything, I'd appreciate it.

Android Solutions


Solution 1 - Android

If you're targeting 1.6 or later, you can use the http://developer.android.com/reference/android/view/View.html#attr_android:onClick">android:onClick xml attribute to remove some of the repetitive code. See http://android-developers.blogspot.com/2009/10/ui-framework-changes-in-android-16.html">this blog post by Romain Guy.

<Button 
   android:height="wrap_content"
   android:width="wrap_content"
   android:onClick="myClickHandler" />

And in the Java class, use these below lines of code:

class MyActivity extends Activity {
    public void myClickHandler(View target) {
        // Do stuff
    }
}

Solution 2 - Android

Implement OnClickListener() on your Activity...

public class MyActivity extends Activity implements View.OnClickListener {
}

For each button use...

buttonX.setOnClickListener(this);

In your Activity onClick() method test for which button it is...

@Override
public void onClick(View view) {
    if (View.equals(buttonX))
        // Do something
}

Also in onClick you could use view.getId() to get the resource ID and then use that in a switch/case block to identify each button and perform the relevant action.

Solution 3 - Android

Android lambada solution

public void registerButtons(){
	register(R.id.buttonName1, ()-> {/*Your code goes here*/});
	register(R.id.buttonName2, ()-> {/*Your code goes here*/});
	register(R.id.buttonName3, ()-> {/*Your code goes here*/});
}

private void register(int buttonResourceId, Runnable r){
	findViewById(buttonResourceId).setOnClickListener(v -> r.run());
}

Switch case solution solution

public void registerButtons(){
	register(R.id.buttonName1);
	register(R.id.buttonName2);
	register(R.id.buttonName3);
}

private void register(int buttonResourceId){
	findViewById(buttonResourceId).setOnClickListener(buttonClickListener);
}

private OnClickListener buttonClickListener = new OnClickListener() {

	@Override
	public void onClick(View v){
		switch (v.getId()) {
			case R.id.buttonName1:
				// TODO Auto-generated method stub
				break;
			case R.id.buttonName2:
				// TODO Auto-generated method stub
				break;
			case View.NO_ID:
			default:
				// TODO Auto-generated method stub
				break;
		}
	}
};

Solution 4 - Android

Since setOnClickListener is defined on View not Button, if you don't need the variable for something else, you could make it a little terser like this:

findViewById(R.id.buttonXName).setOnClickListener(new OnClickListener() {
    public void onClick(View v) {
    //DO SOMETHING! {RUN SOME FUNCTION ... DO CHECKS... ETC}
    } 
});

Solution 5 - Android

You can use array to handle several button click listener in android like this: here i am setting button click listener for n buttons by using array as:

Button btn[] = new Button[n]; 

NOTE: n is a constant positive integer

Code example:

//class androidMultipleButtonActions 
package a.b.c.app;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

public class androidMultipleButtonActions extends Activity implements OnClickListener{
    Button btn[] = new Button[3];

    public void onCreate(Bundle savedInstanceState) {	
    super.onCreate(savedInstanceState);
        setContentView(R.layout.main);        
        btn[0] = (Button) findViewById(R.id.Button1);
        btn[1] = (Button) findViewById(R.id.Button2);
        btn[2] = (Button) findViewById(R.id.Button3);
        for(int i=0; i<3; i++){
            btn[i].setOnClickListener(this);
        }        	
    }

    public void onClick(View v) {
        if(v == findViewById(R.id.Button1)){
            //do here what u wanna do.
        }
        else if(v == findViewById(R.id.Button2)){
            //do here what u wanna do.
        }
        else if(v == findViewById(R.id.Button3)){
            //do here what u wanna do.
        }
    }
}

Note: First write an main.xml file if u dont know how to write please mail to: [email protected]

Solution 6 - Android

I think you can usually do what you need in a loop, which is much better than many onClick methods if it can be done.

Check out this answer for a demonstration of how to use a loop for a similar problem. How you construct your loop will depend on the needs of your onClick functions and how similar they are to one another. The end result is much less repetitive code that is easier to maintain.

Solution 7 - Android

Implement Activity with View.OnClickListener like below.

public class MyActivity extends AppCompatActivity implements View.OnClickListener {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_scan_options);

        Button button = findViewById(R.id.button);
        Button button2 = findViewById(R.id.button2);

        button.setOnClickListener(this);
        button2.setOnClickListener(this);
    }

    @Override
    public void onClick(View view) {

        int id = view.getId();

        switch (id) {
            
            case R.id.button:

                  // Write your code here first button

                break;
            
             case R.id.button2:
              
                  // Write your code here for second button

                break;

        }

    }

}

Solution 8 - Android

public class MyActivity extends AppCompatActivity implements View.OnClickListener {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_scan_options);

        Button button = findViewById(R.id.button);
        Button button2 = findViewById(R.id.button2);

        button.setOnClickListener(this);
        button2.setOnClickListener(this);
    }

    @Override
    public void onClick(View view) {

        int id = view.getId();

        switch (id) {

            case R.id.button:

                  // Write your code here first button

                break;

             case R.id.button2:

                  // Write your code here for second button

                break;

        }

    }

}

Solution 9 - Android

public class MainActivity extends AppCompatActivity  implements View.OnClickListener{

    Button b1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        b1=(Button)findViewById(R.id.button);
        b1.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        Toast.makeText(getApplicationContext(),"Button is Working",Toast.LENGTH_LONG).show();
    }

}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionuser591162View Question on Stackoverflow
Solution 1 - AndroiddgmltnView Answer on Stackoverflow
Solution 2 - AndroidSquonkView Answer on Stackoverflow
Solution 3 - AndroidIlya GazmanView Answer on Stackoverflow
Solution 4 - AndroidJim BlacklerView Answer on Stackoverflow
Solution 5 - AndroidWesagnView Answer on Stackoverflow
Solution 6 - AndroidMatthew WillisView Answer on Stackoverflow
Solution 7 - Androidyatin deokarView Answer on Stackoverflow
Solution 8 - Androidraju dhirajView Answer on Stackoverflow
Solution 9 - AndroidAnilView Answer on Stackoverflow