Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find View from string instead of R.id

Tags:

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

like image 975
Tae-Sung Shin Avatar asked Dec 08 '11 23:12

Tae-Sung Shin


People also ask

What does find view by ID do?

findViewById is the method that finds the View by the ID it is given. So findViewById(R. id. myName) finds the View with name 'myName'.

What is the type of R ID?

android. R. id. text1 is just an identifier defined in the Android framework.


2 Answers

You can use something like this:

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

And then use the id.

like image 69
Ted Hopp Avatar answered Oct 14 '22 05:10

Ted Hopp


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) 
like image 37
AlejandroQS Avatar answered Oct 14 '22 04:10

AlejandroQS