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,

+3


source to share


6 answers


You can use tags for this purpose. for example



btn.setTag("btXYZ");

      

+9


source


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;
        }
    }
};

      

+1


source


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);

      

+1


source


No, you cannot set it to String

, the id value int

, even if you set it from XML

, it is just the name of the value resourceint

0


source


No, you cannot set it to String, id value is int, even if you set it from XML, it is just int value resource name

0


source


If you have references to views anyway, you can simply store them all in a HashMap, for example using a HashMap.

Another alternative to avoid any typos is to enumerate as a hashmap key, for example: HashMap.

0


source







All Articles