I have ImageButton
s
and i send a Toast from override fun onCreate(savedInstanceState: Bundle?)
when its clicked successful.
I want loop trough all ImageButton
s to add the setOnClickListener
to them.
this works:
works without a loop:
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
findViewById<ImageButton>(R.id.r1col1).setOnClickListener {
toastContentDescription(it)
}
}
private fun toastContentDescription(it: View) {
val contentDescription = it.contentDescription
val myToast = Toast.makeText(applicationContext, contentDescription, Toast.LENGTH_SHORT)
myToast.show()
}
}
works not, not start anymore
I found a example for Android Java Buttons here: How to get all Buttons ID's in one time on Android
So i modified my code to following. But then the app not start anymore (gives me no errors).
i guess i have to get the id first and then the problem is solved.
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
for (i in 0..4) {
val id: Int = resources.getIdentifier("R.id.r1col$i", "id", this.packageName)
findViewById<ImageButton>(id).setOnClickListener {
toastContentDescription(it)
}
}
}
private fun toastContentDescription(it: View) {
val contentDescription = it.contentDescription
val myToast = Toast.makeText(applicationContext, contentDescription, Toast.LENGTH_SHORT)
myToast.show()
}
}
Is there any way to set the setOnClickListener to all ImageButtons in a loop (etc.) Code?
CodePudding user response:
Remove the "R.id."
prefix from the string you’re passing.