Install button ID programmatically
Android 2.3.3
I have a table with N rows and N columns. For each row, I have to add 4 buttons dynamically and then perform actions based on the button clicked. I know that we can set the button IDs with values Integer with button.setID()
, but I want to know if we can set identifiers in the form of string values that we have set in XML files, such as btnXYZ1
and btnXYZ2
, and so on,
source to share
for (int i=0;i<nob;i++) {
Button btn = new Button(this);
btn.setId(i+1);
btn.setText("Button"+(i+1));
btn.setOnClickListener(btnclick); <<<<<<<set click
btn.setLayoutParams(lprams);
dynamicview.addView(btn);
}
And add this listner outside any method and inside the class
OnClickListener btnclick = new OnClickListener() {
@Override
public void onClick(View view) {
switch(view.getId()) {
case 1:
//first button click
break;
//Second button click
case 2:
break;
case 3:
//third button click
break;
case 4:
//fourth button click
break;
.
.
.
default:
break;
}
}
};
source to share
The strings you use in your XML files correspond to int in R.java and are therefore actually ints. The setId () method only takes an int value as an argument. You can define your ids in the constants file, for example:
public class Ids {
public static final int ID_ONE = 1;
}
and then use it like:
button.setId(Ids.ID_ONE);
source to share