问题
I am having Multiple Strings, that are coming dynamically, I want to set these strings as Id of the EditText Fields in my Form. How can I do that, can you please help me?
For Ex: If I am having id "title", I want to set this title as 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.
回答1:
No, You can't set id with char, String or anything else except int...because, id is maintained by R.java file which contains only int.
You can use setTag() instead of setId().
Use setTag() as below...
edText.setTag("title");
You can later check it using getTag() edText.getTag().
You can use findViewWithTag in order to find the view with a specific tag.
回答2:
You can get the id by reflection. For example, if you have a view in xml which has this id: @+id/select_time Then you can get the int value in Rclass by this way:
String idStr = "select_time";
//com.example.appandroidtest is your app's package name
Class<?> clz = com.example.appandroidtest.R.id.class;
try {
int viewId = (int) clz.getField(idStr).get(null);
} catch (Exception e) {
e.printStackTrace();
}
来源:https://stackoverflow.com/questions/30253695/how-can-i-set-a-dynamic-string-as-an-id-of-an-edittext-field-in-android