android点击按钮控制图片切换-kotlin

android点击按钮控制图片切换-kotlin_第1张图片

class MainActivity : AppCompatActivity() {
     

    override fun onCreate(savedInstanceState: Bundle?) {
     
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        initView()
    }

    private fun initView() {
     
        val chooseGridFriendBtn: Button = findViewById(R.id.chooseGridFriend)
        chooseGridFriendBtn.setOnClickListener {
      chooseGirlFriend() }
    }
    // 选女友的方法实现
    private fun chooseGirlFriend() {
     
        val chooseGirlfriend = ChooseGirlfriend(5) // 只有5张图
        val girlFriend = chooseGirlfriend.renderChoose()
        Toast.makeText(this, "" + girlFriend, Toast.LENGTH_SHORT).show()

        // 显示对应图片
        val girlFriendImageSource =  when (girlFriend){
     
            1 -> R.drawable._0
            2 -> R.drawable._1
            3 -> R.drawable._2
            4 -> R.drawable._3
            5 -> R.drawable._4
            else -> R.drawable.dice
        }

        // 展示选中图片
        val girlFriendImageView: ImageView = findViewById(R.id.imageView)
        girlFriendImageView.setImageResource(girlFriendImageSource)

    }

}

/*
* 女友选择器
* 随机数选择 默认1-6
* */

class ChooseGirlfriend(private val numDice: Int = 6) {
     
    fun renderChoose(): Int {
     
        return (1..numDice).random()
    }
}


<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".MainActivity">
    
    <ImageView
        android:id="@+id/imageView"
        android:layout_width="215dp"
        android:layout_height="150dp"
        android:layout_gravity="center"
        android:layout_marginVertical="20dp"
        android:contentDescription="@string/dice_image"
        app:srcCompat="@drawable/dice" />

    <Button
        android:id="@+id/chooseGridFriend"
        android:layout_width="237dp"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:text="@string/choose_a_girlfriend" />
LinearLayout>

你可能感兴趣的:(android,android,kotlin)