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
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'.
android. R. id. text1 is just an identifier defined in the Android framework.
You can use something like this:
Resources res = getResources(); int id = res.getIdentifier("titleText", "id", getContext().getPackageName());
And then use the id.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With