[android] Android Button setOnClickListener Design

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.

This question is related to android button design-patterns onclicklistener

The answer is


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}
    } 
});

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;

        }

    }

}

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;
        }
    }
};

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.


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;

        }

    }

}

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();
    }

}

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]


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.


Examples related to android

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How to implement a simple scenario the OO way My eclipse won't open, i download the bundle pack it keeps saying error log getting " (1) no such column: _id10 " error java doesn't run if structure inside of onclick listener Cannot retrieve string(s) from preferences (settings) strange error in my Animation Drawable how to put image in a bundle and pass it to another activity FragmentActivity to Fragment A failure occurred while executing com.android.build.gradle.internal.tasks

Examples related to button

How do I disable a Button in Flutter? Enable/disable buttons with Angular Disable Button in Angular 2 Wrapping a react-router Link in an html button CSS change button style after click Circle button css How to put a link on a button with bootstrap? What is the hamburger menu icon called and the three vertical dots icon called? React onClick function fires on render Run php function on button click

Examples related to design-patterns

How to implement a simple scenario the OO way Implementing Singleton with an Enum (in Java) What is difference between MVC, MVP & MVVM design pattern in terms of coding c# Best Practices for mapping one object to another REST API Login Pattern When should we use Observer and Observable? How to implement a FSM - Finite State Machine in Java Function in JavaScript that can be called only once Thread Safe C# Singleton Pattern Repository Pattern Step by Step Explanation

Examples related to onclicklistener

Android - setOnClickListener vs OnClickListener vs View.OnClickListener Null pointer Exception on .setOnClickListener Multiple Buttons' OnClickListener() android Android setOnClickListener method - How does it work? RecyclerView onClick How do I open a new fragment from another fragment? Why is this jQuery click function not working? Android button onClickListener Android: how to handle button click Adding an onclicklistener to listview (android)