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?