How to set dynamic string as ID of Edittext field in android
I have multiple lines that go dynamically, I want to set these lines as the ID of the EditText fields in my form. How can I do this, can you help me?
For example: if I have the id "title", I want to set this title as the ID of the EditText field, so that when I want to access the value of this field, I can access it like findviewById (title).
Please help me here ...
Thank you so much in advance.
source to share
No . You cannot install id
with char
, String
or anything else except int
... because, it is id
supported by a file R.java
that only contains int
.
You can use setTag()
instead setId()
.
Use setTag()
as shown below.
edText.setTag("title");
You can check it later with getTag () edText.getTag ().
You can use findViewWithTag to find a view with a specific tag.
source to share
You can get the ID by reflection. For example, if you have a view in xml that has this id: @+id/select_time
Then you can get the int value in the class R
like this:
String idStr = "select_time";
//com.example.appandroidtest is your app package name
Class<?> clz = com.example.appandroidtest.R.id.class;
try {
int viewId = (int) clz.getField(idStr).get(null);
} catch (Exception e) {
e.printStackTrace();
}
source to share