Setting Button ID programmatically

2019-02-11 01:00发布

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 button IDs with Integer values with button.setID(), but I want to know whether we can set IDs as string values as we set in XML files, such as btnXYZ1 and btnXYZ2 etc.,

6条回答
趁早两清
2楼-- · 2019-02-11 01:19

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

查看更多
Animai°情兽
3楼-- · 2019-02-11 01:24
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 the any method and inside 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;
        }
    }
};
查看更多
在下西门庆
4楼-- · 2019-02-11 01:27

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:

public class Ids {
    public static final int ID_ONE = 1;
}

and then use it as:

button.setId(Ids.ID_ONE);
查看更多
贼婆χ
5楼-- · 2019-02-11 01:31

You can use tags for that purpose . For example

btn.setTag("btXYZ");
查看更多
我欲成王,谁敢阻挡
6楼-- · 2019-02-11 01:32

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

查看更多
兄弟一词,经得起流年.
7楼-- · 2019-02-11 01:32

If you have the references to the views anyway , you can simply save them all into a HashMap, for example using HashMap .

Another alternative , so that you will avoid any typos , is to have an enum as the key of the hashMap , for example : HashMap .

查看更多
登录 后发表回答