Dynamically Set ID to a Button in Android

我只是一个虾纸丫 提交于 2019-12-07 17:40:37

问题


I want to dynamically create a button but am having an issue when it comes to setting an ID for it. I tried putting an integer value in there but keep getting an error that says "Expected Resource of Type ID." The issue is that I DONT want to create this Button in my XML file and yet I need a way to track it with an ID. Please Help.

Button changeButton = new Button(getApplicationContext());
changeButton.setText("Change");
changeButton.setId(1);//Keep Getting an error here

回答1:


In your res/values folder you can keep an ids.xml file, where you can define:

<resources>
   <item type="id" name="your_button_id"/>
   ...
</resources>

Then, you can use it in your code:

changeButton.setId(R.id.your_button_id);



回答2:


If your goal is to track it, you could try setTag:

 changeButton.setTag("any_tag");

Notice that the tag is of type Object, meaning it could be any object you want (String, int, Date, CustomeObject, ...etc).



来源:https://stackoverflow.com/questions/32127881/dynamically-set-id-to-a-button-in-android

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!