How can I set a dynamic string as an Id of an Edittext Field in android

﹥>﹥吖頭↗ 提交于 2019-12-12 09:37:15

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!