kotlinimagebutton

howTo get Image Resource of a ImageButton in kotlin


i want change the ImageResource of a ImageButton that i have find by id.

Motivation

a ImageButton(bottom) works as a reminder/backup of the last click of a ImageButton(top) .

setup:

example without errors, but don't find ImageResource of idR1

findViewById<ImageButton>(idR1).setOnClickListener {
    findViewById<ImageButton>(idR5_oppCiv).setImageResource(R.drawable.athen_cavalry_swordsman);

not working examples

findViewById<ImageButton>(idR1).setOnClickListener {
    findViewById<ImageButton>(idR5_oppCiv).setImageResource(it.resources.getDrawable());
findViewById<ImageButton>(idR1).setOnClickListener {
    findViewById<ImageButton>(idR5_oppCiv).setImageResource(it.getImageResource());

try to get and set Drawable

following causes the app to crash when i click on an ImageButton. Here i use a defType "res" to get the resource (the image hopefully).

val resR1: Int = resources.getIdentifier("r1col$i", "res", this.packageName)
findViewById<ImageButton>(idR1).setOnClickListener {
    findViewById<ImageButton>(idR5_oppCiv).setImageDrawable(getDrawable(resR1))

How could i get this image resource of it ? And use it for the other ImageButton?


Solution

  • You should be setting the image like using setImageDrawable like this.

        val image = findViewById<ImageButton>(R.id.your_view_id)
        image.setOnClickListener {
        findViewById<ImageButton>(idR5_oppCiv).setImageDrawable(image.drawable)
    }