How to set the text of a Button using getResources() in Kotlin? - android

I'm trying to identify a button using getResources() and getIdentifier(), then set the text for it. The below code shows how I thought it should work (simply setting the ID and setting the text for the object).
while (c < 65) {
val resID = getResources().getIdentifier("S1", "id", getPackageName())
resID.text = ""
}
Instead I get an error, with ".text" showing red. How should I go about setting this up to run how I expected.

resID is the integer id of a Button "named" S1.
Use it to find the Button:
val resID = resources.getIdentifier("S1", "id", getPackageName())
val button = findViewById<Button>(resID)
button.text = ""

based on Docs getIdentifier returns Int , so you need findViewById and use the getIdentifier result in order to use the object

Kotlin Extensions do not work if the referenced int is not coming from R.id.
Button is a view, then you can access to it by using
findViewById<Button>(buttonId)
If you want to retrieve id from resources, just getResources().getIdentifier("S1", "id", getPackageName())
In conclusion, you see how this is going to be:
val buttonId = getResources().getIdentifier("S1", "id", getPackageName())
val button = findViewById<Button>(buttonId)
button.setText("")

Related

Converting string containing id to an id type Int

I have a string that contains an id for a button:
val stringContainingId = "R.id.testBtn"
And I testBtn is set as id in activity_main:
<Button
android:id="#+id/testBtn"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
So, I want to set the text of this button in my MainActivity. stringContainingId is a string, so I have to convert to id with type Int:
val id: Int = applicationContext.resources.getIdentifier("R.id.testBtn", "id", applicationContext.packageName)
Then changing the text of testBtn:
val testBtn = findViewById<Button>(id)
testBtn.text = "Other text"
But at runtime app crashes, and shows this error:
testBtn must not be null
But if changed to findViewById<Button>(R.id.testBtn), eveything goes smoothly.
What's wrong with variable 'id' that is getting the id from string?
In the Android Java framework, android.R.id.testBtn is an identifier of a Button . You can find it in many layouts from the framework (select_dialog_item, select_dialog_singlechoice, simple_dropdown_item_1line, etc.). In Android framework xml, it is represented by #+id/testBtn
Mate, you get id = 0 cause by R.id.testBtn not a String. It actually an int variable. If you want to get identifier, you just need add testBtn to find it.
val id: Int = applicationContext.resources.getIdentifier(testBtn, "id", applicationContext.packageName)
Read more in document official android and I believe you know more than.
e.g: https://www.codota.com/code/java/methods/android.content.res.Resources/getIdentifier
What is "android.R.id.text1"?
https://developer.android.com/reference/kotlin/android/R.id
Use just “testBtn”, not “R.id.testBtn” in getIdentifier().

Find button by ID in Kotlin

I have a user interface with multiple buttons. They have the IDs "button1", "button2", ...
I want to set an OnClickListener for all of them in a for loop. I dont want to type a line like button1.setOnClickListener for every button.
I have found one solution that works in java here: Android: Using findViewById() with a string / in a loop
And I tried to adapt it in Kotlin.
var buttons = ArrayList<Button>()
for (i in 1..7) {
var idString = "Button%i"
var buttonID = getResources().getIdentifier(idString, "id", packageName)
buttons.add( findViewWithTag(buttonID))
buttons[i].setOnClickListener(buttonclicked)
}
This throws an "Unresolved Reference" error. How can I access all buttons without typing a line for each of them?
Thanks in advance to all of you.
You call findViewWithTag() instead of findViewById() in your code.
Also you are not doing string interpolation correctly by var idString = "Button%i".
Change to this:
val buttons = ArrayList<Button>()
for (i in 1..7) {
val idString = "Button$i"
val buttonID = resources.getIdentifier(idString, "id", packageName)
buttons.add(findViewById(buttonID))
buttons[i].setOnClickListener(buttonclicked)
}

How to select a drawable image by matching a string value to the image name?

I have an arraylist of strings, I need to randomly select an index and if the string value was
"bear", then set background of button to bear.jpg.
OK, my research shows that resources are accessed by an int id, not their name, I am not sure the best way to achieve what I want to do. Here is my code:
list.add("alligator");
list.add("bear");
list.add("beaver");
list.add("bison");
randomInt = randomGenerator.nextInt(list.size());
b1.setBackgroundResource(R.drawable.list.get(randomInt));
Now of course the last line of the code is wrong, I wrote it to show what I want to achieve. My latest attempt to accomplish this was trying to get the resource id and access the resource this way, but I don't know if this is the way to do this, and if it is I am not using the correct code. I am trying hard to do this by myself but I could use some advice on what to do here. Here is my attempt:
String mDrawableName = "bear";
int resID = getResources().getIdentifier(mDrawableName , "drawable", getPackageName());
String s= Integer.toString(resID);
Use the below code
int resID = getResources().getIdentifier(mDrawableName , "drawable", getPackageName());
b1.setBackgroundResource(resID);
Try this:
list.add("alligator");
list.add("bear");
list.add("beaver");
list.add("bison");
randomInt = randomGenerator.nextInt(list.size());
int resourceId = getResources().getIdentifier(list.get(randomInt), "drawable", getPackageName());
b1.setBackgroundResource(resourceId);

How do a load a specific drawable by using a string/int?

If I have a variable with the number associated with a gridview position (id int 14) how do I make the code below load the correct drawable? (ie hccat14)
mBitmap = getImageFromResource(getContext(), R.drawable.hccat14,w, h);
Thanks,
Shannon
I don't know exactly how you are trying to use it, but it should be something like this.
String resouceName = "hccat" + Integer.toString(14);
int resourceID = getResources().getIdentifier(resourceName,
"drawable", getPackageName());
Here's what I use, just set the stringName on click
imageResource = Classname.this.getResources().getIdentifier(stringName,
null, null);
mBitmap.setImageResource(imageResource);
EDIT I store the image name as packagename:drawable/imagename in my database

How to find View from string instead of R.id

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?
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)

Categories

Resources