Reputation: 34
I want to know the simple way to add onclicklistener on all button. button can more then 20-30. for eg..
Button1 Id = "Submit"; Button2 Id = "Cancel" so on...
Button b1 = (Button) findViewById(R.id.button1);
Button b2 = (Button) findViewById(R.id.button2);
Button b3 = (Button) findViewById(R.id.button3);
b1.setOnClickListener(this);
b2.setOnClickListener(this);
b3.setOnClickListener(this);
Upvotes: 0
Views: 457
Reputation: 81559
Just use ButterKnife library like this:
@OnClick({ R.id.btndoor1, R.id.btndoor2, R.id.btndoor3 })
public void pickDoor(Button door) {
if (door.hasPrizeBehind()) {
Toast.makeText(this, "You win!", LENGTH_SHORT).show();
} else {
Toast.makeText(this, "Try again", LENGTH_SHORT).show();
}
}
Where you have to inject the onClick()
into the buttons like this
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_example, container, false);
ButterKnife.inject(this, rootView);
Upvotes: 0
Reputation: 1543
Try this :
for(int i=0; i < ((ViewGroup)getView()).getChildCount(); i++) {
View v = ((ViewGroup)getView()).getChildAt(i);
if(v instanceof Button) {
v.setOnClickListener(this);
}
}
Upvotes: 0
Reputation: 543
First, create a button array:
Button[] buttons = new Button[number_of_buttons];
Taking into account your ids, you could do the following:
for(int i=0; i<buttons.length; i++)
{
buttons[i]=(Button)findViewById(getResources().getIdentifier("button"+i,
"id", getPackageName());
buttons[i].setOnClickListener(this);
}
Upvotes: 1
Reputation: 47817
Set android:onClick="mainMenuButtonClick"
to your all buttons in XML and add mainMenuButtonClick()
your activity and used switch case
to identify Button like:
public void mainMenuButtonClick(View v) {
switch (v.getId()) {
case R.id.Button1:
break;
case R.id.Button2:
break;
case R.id.crmButton:
break;
case R.id.Button3:
break;
case R.id.Button4:
break;
case R.id.Button5:
break;
}
}
Upvotes: 2