在Android中将ID动态设置为按钮 [英] Dynamically Set ID to a Button in Android
本文介绍了在Android中将ID动态设置为按钮的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想动态创建一个按钮,但是在为其设置ID时遇到问题.我尝试在其中放置一个整数值,但始终收到表示"Expected Resource of Type ID."
的错误.问题是我不想在我的XML文件中创建此Button,但是我需要一种使用ID来跟踪它的方法.请帮忙.
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
推荐答案
在res/values文件夹中,您可以保留一个ids.xml文件,您可以在其中定义:
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);
这篇关于在Android中将ID动态设置为按钮的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文