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

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

Posted by: admin June 15, 2020 Leave a comment

Questions:

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.

How to&Answers:

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.

Answer:

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