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

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

40425 次浏览

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.

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);

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

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);

Here's my solution as an extension function in kotlin:

/* sets a valid id that isn't in use */
fun View.findAndSetFirstValidId() {
var i: Int
do {
i = Random.nextInt()
} while (findViewById<View>(i) != null)
id = i
}