I am creating an EditText
object which I then try to reference in a unit test. What is the best way to add a new id
to R.id
for this dynamically created object, so that I can later reference it via findViewById()
in the unit test?
Asked
Active
Viewed 4.1k times
93
-
possible duplicate of [Android: View.setID(int id) programmatically - how to avoid ID conflicts?](http://stackoverflow.com/questions/1714297/android-view-setidint-id-programmatically-how-to-avoid-id-conflicts) – rds Jul 21 '14 at 17:51
3 Answers
222
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);

Austyn Mahoney
- 11,398
- 8
- 64
- 85

Hidden Android
- 2,754
- 2
- 18
- 10
-
1
-
2Sorry for the late reply, but yeah, as with all Android resources, you can name that .xml anyway you like... – Hidden Android Aug 24 '15 at 00:26
2
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);

Shojaeddin
- 1,851
- 1
- 18
- 16
0
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
}

Amin Keshavarzian
- 3,646
- 1
- 37
- 38