Android 以编程方式将 id 添加到 R.id

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3216294/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-20 09:11:07  来源:igfitidea点击:

programmatically add id to R.id

androidandroid-edittextunit-testing

提问by Ben

I am creating an EditTextobject which I then try to reference in a unit test. What is the best way to add a new idto R.idfor this dynamically created object, so that I can later reference it via findViewById()in the unit test?

我正在创建一个EditText对象,然后我尝试在单元测试中引用它。什么是添加一个新的最佳方式idR.id为这个动态创建的对象,这样我可以通过以后引用它findViewById()的单元测试?

回答by Hidden Android

You can set ID's you'll use later in R.id class using an xml resource file, and let Android SDK give them unique values during compile time.

您可以使用 xml 资源文件设置稍后将在 R.id 类中使用的 ID,并让 Android SDK 在编译时为它们提供唯一值。

res/values/ids.xml

res/values/ids.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>

    <item name="my_edit_text_1" type="id"/>
    <item name="my_button_1" type="id"/>
    <item name="my_time_picker_1" type="id"/>

</resources>

To use it in code:

在代码中使用它:

myEditTextView.setId(R.id.my_edit_text_1);

回答by Liam

You can use setId for every view and assign any positive number, based on google developer:

您可以根据谷歌开发人员为每个视图使用 setId 并分配任何正数:

Sets the identifier for this view. The identifier does not have to be unique in this view's hierarchy. The identifier should be a positive number.Link

设置此视图的标识符。该标识符在此视图的层次结构中不必是唯一的。标识符应为正数。关联

so you can use

所以你可以使用

EveryView.setId(int);