Skip to content Skip to sidebar Skip to footer

Setting Button Id Programmatically

Android 2.3.3 I have a table with N rows and N columns. For each row, I should add 4 buttons dynamically, and later do actions based on the button clicked. I know we can set the bu

Solution 1:

You can use tags for that purpose . For example

btn.setTag("btXYZ");

Solution 2:

for (int i=0;i<nob;i++) {
     Button btn = newButton(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 the any method and inside class

OnClickListenerbtnclick=newOnClickListener() {

    @OverridepublicvoidonClick(View view) {

        switch(view.getId()) {
            case1:
                //first button clickbreak;
                //Second button clickcase2:
                break;
            case3:
                //third button clickbreak;
            case4:
                //fourth button clickbreak;
             .
             .
             .
            default:
                break;
        }
    }
};

Solution 3:

The strings you use in your XML files correspond to an int in R.java, and are hence actually ints. The setId() method will only accept an int value as an argument. You could define your IDs in a constants file, something like:

publicclassIds {
    publicstaticfinalint ID_ONE = 1;
}

and then use it as:

button.setId(Ids.ID_ONE);

Solution 4:

No you cannot set it to String, the id is int value, even when you set it from XML it is just the resource name of an int value

Solution 5:

No you cannot set it to String, the id is int value, even when you set it from XML it is just the resource name of an int value

Post a Comment for "Setting Button Id Programmatically"