Multiple Buttons' OnClickListener() android

AndroidOnclicklistener

Android Problem Overview


I'm currently making a simple calculator app on Android. Im trying to set up the code so that when a number button is pressed it updates the calculator screen with that number. Currently I'm doing it like this.

    Button one = (Button) findViewById(R.id.oneButton);
	one.setOnClickListener(new View.OnClickListener() {
		
		@Override
		public void onClick(View v) {
			TextView output = (TextView) findViewById(R.id.output);
			output.append("1");
		}
	});

It works but I'm writing this same code for every single button on the calculator. As you can imagine it is very redundant. Is there anyway I can write this code in a more efficient way? One that involves not writing this method for every single button?

Android Solutions


Solution 1 - Android

You Just Simply have to Follow these steps for making it easy...

You don't have to write new onClickListener for Every Button... Just Implement View.OnClickLister to your Activity/Fragment.. it will implement new Method called onClick() for handling onClick Events for Button,TextView` etc.

> 1. Implement OnClickListener() in your Activity/Fragment

public class MainActivity extends Activity implements View.OnClickListener {

}

> 2. Implement onClick() method in your Activity/Fragment

public class MainActivity extends Activity implements View.OnClickListener {
    
    @Override
	protected void onCreate(Bundle savedInstanceState) {
	    super.onCreate(savedInstanceState);
    }
    
    @Override
    public void onClick(View v) {
      // default method for handling onClick Events..
    }
}

> 3. Implement OnClickListener() For Buttons

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    
    setContentView(R.layout.your_layout);
    
    Button one = (Button) findViewById(R.id.oneButton);
    one.setOnClickListener(this); // calling onClick() method
    Button two = (Button) findViewById(R.id.twoButton);
    two.setOnClickListener(this);
    Button three = (Button) findViewById(R.id.threeButton);
    three.setOnClickListener(this);
}

> 4. Find Buttons By Id and Implement Your Code..

@Override
public void onClick(View v) {
    switch (v.getId()) {
        case R.id.oneButton:
            // do your code
            break;
        case R.id.twoButton:
            // do your code
            break;
        case R.id.threeButton:
            // do your code
            break;
        default:
            break;
    }
}

Please refer to this link for more information :

https://androidacademic.blogspot.com/2016/12/multiple-buttons-onclicklistener-android.html (updated)

This will make easier to handle many buttons click events and makes it looks simple to manage it...

Solution 2 - Android

You could set the property:

android:onClick="buttonClicked"

in the xml file for each of those buttons, and use this in the java code:

public void buttonClicked(View view) {

	if (view.getId() == R.id.button1) {
        // button1 action
	} else if (view.getId() == R.id.button2) {
		//button2 action
	} else if (view.getId() == R.id.button3) {
        //button3 action
    }

}

Solution 3 - Android

Set a Tag on each button to whatever you want to work with, in this case probably an Integer. Then you need only one OnClickListener for all of your buttons:

Button one = (Button) findViewById(R.id.oneButton);
Button two = (Button) findViewById(R.id.twoButton);
one.setTag(new Integer(1));
two.setTag(new Integer(2));

OnClickListener onClickListener = new View.OnClickListener() {

    @Override
    public void onClick(View v) {
        TextView output = (TextView) findViewById(R.id.output);
        output.append(v.getTag());
    }
}

one.setOnClickListener(onClickListener);
two.setOnClickListener(onClickListener);

Solution 4 - Android

I created dedicated class that implements View.OnClickListener.

public class ButtonClickListener implements View.OnClickListener {

    @Override
    public void onClick(View v) {
        Toast.makeText(MainActivity.this, "Button Clicked", Toast.LENGTH_SHORT).show();
    }

}

Then, I created an instance of this class in MainActivity

private ButtonClickListener onClickBtnListener = new ButtonClickListener();

and then set onClickListener for button

btn.setOnClickListener(onClickBtnListener);

Solution 5 - Android

public class MainActivity extends AppCompatActivity implements OnClickListener  {
    Button  b1,b2;
    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        b1= (Button) findViewById(R.id.button);
        b2= (Button) findViewById(R.id.button2);
        b1.setOnClickListener(this);
        b2.setOnClickListener(this);
    }


    @Override
    public void onClick(View v)
    {
        if(v.getId()==R.id.button)
        {
            Intent intent=new Intent(getApplicationContext(),SignIn.class);
            startActivity(intent);
        }
        else if (v.getId()==R.id.button2)
        {
            Intent in=new Intent(getApplicationContext(),SignUpactivity.class);
            startActivity(in);
        }
    }
}

Solution 6 - Android

You can use this

    TextView output = (TextView) findViewById(R.id.output);
    one.setOnClickListener(youractivity.this);
    // set the onclicklistener for other buttons also
    
    @Override
    public void onClick(View v) {
      int id = v.getId();
    switch(id) {
    case R.id.oneButton:      
       append("1",output);
       break;
    case R.id.twoButton:
        append("2",output);
       break;
    case R.id.threeButton:
        append("3",output);
       break;
     } 
      }
    
 private void append(String s,TextView t){
  t.setText(s); 
}
  

you can identify the views in your activity in a separate method.

Solution 7 - Android

I had a similar issue and what I did is: Create a array of Buttons

Button buttons[] = new Button[10];

Then to implement on click listener and reference xml id's I used a loop like this

for (int i = 0; i < 10; i++) {		
String buttonID = "button" + i;
		int resID = getResources().getIdentifier(buttonID, "id",
				"your package name here");
		buttons[i] = (Button) findViewById(resID);
		buttons[i].setOnClickListener(this);
	}

But calling them up remains same as in Prag's answer point 4. PS- If anybody has a better method to call up all the button's onClick, please do comment.

Solution 8 - Android

Implement onClick() method in your Activity/Fragment public class MainActivity extends Activity implements View.OnClickListener {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public void onClick(View v) {
 switch (itemId) {

// if you call the fragment with nevigation bar then used.

           case R.id.nav_menu1:
                fragment = new IntroductionFragment();
                break;
           
// if call activity with nevigation bar then used.
          
            case R.id.nav_menu6:
                Intent i = new Intent(MainActivity.this, YoutubeActivity.class);
                startActivity(i);
      // default method for handling onClick Events..
    }
}

Solution 9 - Android

public void onClick(View v) {
    int id = v.getId();
    switch (id){
        case R.id.button1:
            //do ur code
            Toast.makeText(this,"This is button 1",Toast.LENGTH_SHORT).show();
            break;
        case R.id.button2:
            Intent intent = new Intent(this,SecondActivity.class);
            Intent.putExtra("key",value);
            startActivity(intent);
            break;
        case R.id.button3:
            //do ur code
            break;
        case R.id.button4:
            //do ur code;
            break;
        default:
            //do ur code;
    }
}

Solution 10 - Android

I find that using a long if/else chain (or switch), in addition to the list of findViewById(btn).setOnClickListener(this) is ugly. how about creating new View.OnlickListeners with override, in-line:

findViewById(R.id.signInButton).setOnClickListener(new View.OnClickListener()
    { @Override public void onClick(View v) { signIn(); }});
findViewById(R.id.signOutButton).setOnClickListener(new View.OnClickListener()
    { @Override public void onClick(View v) { signOut(); }});
findViewById(R.id.keyTestButton).setOnClickListener(new View.OnClickListener()
    { @Override public void onClick(View v) { decryptThisTest(); }});
findViewById(R.id.getBkTicksButton).setOnClickListener(new View.OnClickListener()
    { @Override public void onClick(View v) { getBookTickers(); }});
findViewById(R.id.getBalsButton).setOnClickListener(new View.OnClickListener()
    { @Override public void onClick(View v) { getBalances(); }});

Solution 11 - Android

No need of if else's or switch, Let's start: In your every Button or whatever it is (I am using ImageView), Add this attribute android:onClick="DoSomeThing"

In your Activity:

public void DoSomeThing(View v){
    ImageView img1= (ImageView) v; //you have to cast the view i.e. if it's button, it must be cast to Button like below line

    Button b1= (Button) v;

    img1.setImageBitmap(imageBitmap); //or anything you want to do with your view, This will work for all

    b1.setText("Some Text");
 

}

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
Questionuser3011685View Question on Stackoverflow
Solution 1 - AndroidPragnesh Ghoda シView Answer on Stackoverflow
Solution 2 - AndroidAndroView Answer on Stackoverflow
Solution 3 - AndroidHenrik ChristensenView Answer on Stackoverflow
Solution 4 - AndroidVadim NovitskiyView Answer on Stackoverflow
Solution 5 - Androiduser6863325View Answer on Stackoverflow
Solution 6 - Androiduser3905781View Answer on Stackoverflow
Solution 7 - AndroidAkshit AgarwalView Answer on Stackoverflow
Solution 8 - AndroidVicky MahaleView Answer on Stackoverflow
Solution 9 - AndroidSazidur RahmanView Answer on Stackoverflow
Solution 10 - AndroidmholbergerView Answer on Stackoverflow
Solution 11 - AndroidZubair YounasView Answer on Stackoverflow