android – How to find View from string instead of R.id-ThrowExceptions

Exception or error:

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

How to solve:

You can use something like this:

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

And then use the id.

Leave a Reply

Your email address will not be published. Required fields are marked *