首页 > 解决方案 > 如何在点击按钮时来回切换图像和文本?

问题描述

第一次点击按钮时,image1 和 text1 都更改为 image2 和 text2。如何在我第二次点击按钮时将图像和文本都更改回第 1 组,并在我第 3 次点击按钮时将它们更改为第 2 组?

这是我当前的代码:

class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
    }
    fun eating(view: View?) {
        val afterEatingText:String="I am so full!!"
        displayMessage(afterEatingText)
        displayImage(R.drawable.after_cookie)
    }
    private fun displayMessage(message: String) {
        val afterEatingText = findViewById<View>(R.id.before_eating) as TextView
        afterEatingText.text = message
    }
    private fun displayImage(imagesource: Int){
        val afterEatingImage: ImageView = findViewById<View>(R.id.before_cookie) as ImageView
        afterEatingImage.setImageResource(imagesource)
    }
}

标签: androidkotlin

解决方案


 var isClick:Boolean=false
 var  afterEatingText :TextView?=null
 var afterEatingImage:ImageView?=null

class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)
    afterEatingImage= findViewById<ImageView>(R.id.before_cookie)  // find your id you can also direct call with its ids in kotlin
    afterEatingText = findViewById<ImageView>(R.id.before_eating)
}
fun eating(view: View?) {
  if(isClick){
     isClick=true
      // set your first image and text
  }else {
     isClick=false
    val afterEatingText:String="I am so full!!"
    displayMessage(afterEatingText)
    displayImage(R.drawable.after_cookie)
}}
private fun displayMessage(message: String) {
    afterEatingText.text = message
}
private fun displayImage(imagesource: Int){
    afterEatingImage.setImageResource(imagesource)
}

}


推荐阅读