Trade an image with Kotlin?

Asked

Viewed 15 times

0

Hello I am new learning Kotlin and I have the following problem, I have a View image with two buttons, move forward and backward. In a gallery of 5 photos I would like to keep exchanging images so that one button forward an image and the other back. Someone can help?

That’s my mainactivity code

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.view.View
import android.widget.ImageView

class MainActivity : AppCompatActivity() {
    lateinit var img01: ImageView
    val imgs = intArrayOf(
        R.drawable.p0,
        R.drawable.p1,
        R.drawable.p2,
        R.drawable.p3,
        R.drawable.p4,
        R.drawable.p5,
        R.drawable.p6,
    )
    val x = 0
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        img01 = findViewById(R.id.img01)
    }
    fun anterior(view: View) {

        }
    fun proximo(view: View) {




    }
}```

1 answer

0

Supposing:

  • x is your counter
  • you have a Button with ID avancar and another retroceder

You can make the x is incremented in the method proximo() and decreasing in the method anterior(), followed by the assignment of the corresponding Source from your list imgs[] by index x.

And to make the click on the button call your method, you need to pass an onClickListener, using setOnClickListener on the buttons, like this:

class MainActivity : AppCompatActivity() {
    lateinit var img01: ImageView
    lateinit var btnAvancar: Button
    lateinit var btnRetroceder: Button
    val imgs = intArrayOf( 
        R.drawable.p0,
        R.drawable.p1,
        R.drawable.p2,
        R.drawable.p3,
        R.drawable.p4,
        R.drawable.p5,
        R.drawable.p6,
    )
    var x = 0 //alterando de val pra var pra poder incrementar
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        img01 = findViewById(R.id.img01)
        btnAvancar = findViewById(R.id.avancar)
        btnRetroceder = findViewById(R.id.retroceder)

        // especificando o comportamento no clique dos botões
        btnAvancar.setOnClickListener {
            anterior(it)
        }

        btnRetroceder.setOnClickListener {
            proximo(it)
        }
    }
    fun anterior(view: View) {
        if (x > 0) {
            x -= 1
            img01.setImageResource(imgs[x])
        }
    }
    fun proximo(view: View) {
        if (x < imgs.size-1) {
            x += 1
            img01.setImageResource(imgs[x])
        }
    }
...
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.