I have set up 10 buttons in xml and added to main activity. I show only 2. All button just change a variable and button colors. Is there a method to group all the button to a single onclicklistener and use switch to check which button was pressed. using separate onclicklistener seems like allot of waisted space.
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
f1 =(Button) findViewById(R.id.f1);
f2 =(Button) findViewById(R.id.f2);
f1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
clearbutton();
f1.setBackgroundColor(Color.RED);
intbtnSelect=0;
}
});
f2.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
clearbutton();
f2.setBackgroundColor(Color.RED);
intbtnSelect=1;
}
});
You can implement OnClickListener
into your Activity
. For instance
public class MyActivity extends Activity implements View.OnClickListener {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
f1 =(Button) findViewById(R.id.f1);
f1.setOnClickListener(this);
f2 =(Button) findViewById(R.id.f2);
f2.setOnClickListener(this);
}
}
Them you have to implement the onClick method and switch upon view.getId():
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.f1:
// your code here
break;
case R.id.f2:
// your code here
break;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With