java Android 以编程方式创建 ID
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15139310/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Android create ID programmatically
提问by user1173536
I am looking for creating ID in code without using XML declaration. For example, I have code, where I programmatically create View like this
我正在寻找在不使用 XML 声明的情况下在代码中创建 ID。例如,我有代码,我在其中以编程方式创建这样的视图
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.new_layout);
LinearLayout ll = (LinearLayout)findViewById(R.id.layout);
View v = new View(this);
v.setBackgroundColor(0xFFFF0000);
ll.addView(v, 100, 100);
}
and I can add v.setId(50)
, but I would like add v.setId(R.id.some_id)
and I wouldn't like add some_id
into xml file, this option I know.
我可以添加v.setId(50)
,但我想添加但我不想v.setId(R.id.some_id)
添加some_id
到 xml 文件中,这个选项我知道。
My question is, how to create R.id.some_id
programmatically without setting it in XML file. Thanks
我的问题是,如何在R.id.some_id
不将其设置在 XML 文件中的情况下以编程方式创建。谢谢
回答by burmat
Refer to this fantastic answer: https://stackoverflow.com/a/13241629/586859
参考这个奇妙的答案:https: //stackoverflow.com/a/13241629/586859
R.* references are used explicitly to access resources. What you are trying to do is not really possible, but maybe you could us something like the following section from the above answer:
R.* 引用显式用于访问资源。您尝试做的事情实际上不太可能,但也许您可以从上面的答案中找到类似以下部分的内容:
Reserve an XML android:id
for use in code
保留 XMLandroid:id
以在代码中使用
If your ViewGroup
cannot be defined via XML (or you don't want it to be) you can reserve the id via XML to ensure it remains unique:
如果您ViewGroup
不能通过 XML 定义(或者您不希望它被定义),您可以通过 XML 保留 id 以确保它保持唯一:
Here, values/ids.xmldefines a custom id
:
这里,values/ids.xml定义了一个自定义id
:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<item name="reservedNamedId" type="id"/>
</resources>
Then once the ViewGroup or View has been created, you can attach the custom id
然后一旦创建了 ViewGroup 或 View,您就可以附加自定义 id
myViewGroup.setId(R.id.reservedNamedId);