How to find View from string instead of R.id

19,156

Solution 1

You can use something like this:

Resources res = getResources();
int id = res.getIdentifier("titleText", "id", getContext().getPackageName());

And then use the id.

Solution 2

In Kotlin you can use this line to get the ID.

val id: Int = resources.getIdentifier("titleText", "id", packageName)

The returned value can be use as parameter of the function findViewById<TextView>(id).

NOTE: If is called outside of an activity use the context.

val id: Int = context.resources.getIdentifier("titleText", "id", context.packageName)
Share:
19,156

Related videos on Youtube

Tae-Sung Shin
Author by

Tae-Sung Shin

Updated on June 04, 2022

Comments

  • Tae-Sung Shin
    Tae-Sung Shin almost 2 years

    Let's assume I have this in layout of res in my app

        <TextView android:id="@+id/titleText" android:layout_width="fill_parent"
            android:layout_height="wrap_content" android:text="@string/app_name"
            android:textColor="#ffffffb0" android:padding="5px" />
    

    In my activity, I get the TextView using this command

     TextView tv = (TextView)findViewById(R.id.titleText);
    

    But I am looking for another method like this

     TextView tv = (TextView)findViewByString("R.id."+"titleText");
    

    because I need to enumerate those ids. Can any of you give a hint or clue how I can go about it? Thanks

  • klys
    klys almost 6 years
    and what about in kotlin?
  • Ted Hopp
    Ted Hopp almost 6 years
    @JrJimnz - You use exactly the same method calls and just change the syntax for declaring the variables. See here for instance.