Amy
Amy

Reputation: 1390

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?

Upvotes: 0

Views: 585

Answers (2)

Tenfour04
Tenfour04

Reputation: 93789

Use just “testBtn”, not “R.id.testBtn” in getIdentifier().

Upvotes: 0

Loc Le Xuan
Loc Le Xuan

Reputation: 73

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

Upvotes: 1

Related Questions