android - 如何在点击按钮时来回切换图像和文本?
问题描述
第一次点击按钮时,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)
}
}
解决方案
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)
}
}
推荐阅读
- angular - RXJS6 升级:ErrorObservable 没有导出的成员 'ErrorObservable'
- firebase - Firebase 动态链接无法在 iOS 11.3.1 上安装应用程序
- java - 注释中不允许从伴随对象分配的静态最终值
- javascript - 谷歌表格应用脚本查找和替换
- firebase - Spark计划中的Firebase同时连接
- asp.net - 何时在 ASP.NET Core SPA 应用程序中获取 JWT 令牌
- sql - SQL 查询仅包含特定字符的值
- android-studio - 如何禁用在 Android Studio 中穿过屏幕的线条?
- php - cURL POST 请求有效,Guzzle 6 无效
- python - 获取 Numpy 数组的索引