Android按钮设置ClickListener调用函数更改按钮图像
我有一个带有多个按钮的应用程序,图像将根据不同的要求和变量而变化。但是,我无法使图像按钮更改在函数内工作。setOnClickListner将设置函数调用,并在函数中更改按钮内的图像 如何更改按钮中的图像 MainActivity.ktAndroid按钮设置ClickListener调用函数更改按钮图像,android,kotlin,Android,Kotlin,我有一个带有多个按钮的应用程序,图像将根据不同的要求和变量而变化。但是,我无法使图像按钮更改在函数内工作。setOnClickListner将设置函数调用,并在函数中更改按钮内的图像 如何更改按钮中的图像 MainActivity.kt package com.example.sandpit9 import android.support.v7.app.AppCompatActivity import android.os.Bundle import kotlinx.android.synth
package com.example.sandpit9
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import kotlinx.android.synthetic.main.activity_main.*
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
imageButton1.setOnClickListener() { changeimageelement1(R.drawable.button) }
imageButton2.setOnClickListener() { changeimageelement2(R.drawable.button) }
}
}
private fun changeimageelement1(imageButtonX: Int) {
imageButton1.setImageResource(R.drawable.greenbutton)
}
MainActivity.xml
<?xml version="1.0" encoding="utf-8">
<android.support.constraint.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<ImageButton
android:layout_width="174dp"
android:layout_height="154dp" app:srcCompat="@drawable/download"
android:id="@+id/imageButton1"
app:layout_constraintEnd_toEndOf="parent" android:layout_marginEnd="8dp" android:layout_marginRight="8dp"
app:layout_constraintStart_toStartOf="parent" android:layout_marginLeft="8dp"
android:layout_marginStart="8dp" android:layout_marginTop="8dp" app:layout_constraintTop_toTopOf="parent"
android:layout_marginBottom="8dp" app:layout_constraintBottom_toBottomOf="parent"/> .
</android.support.constraint.ConstraintLayout>
.
ClickListener方法应该是setOnClickListener
而不是setOnClickListener
示例代码:
button.setOnClickListener{
counter++
textView.text = "Click counter : $counter"
}
检查教程您不应该在setOnClickListener之后使用()命令,只需使用
button.setOnClickLisener{
//你的行动到此为止
}
是否有错误?您总是在imageButton1
上调用setImageResource
,即使在imageButton2
的onClick侦听器中也是如此。这是故意的吗?既然您不使用参数imageButtonX:Int
,该参数的目的是什么?非常感谢本教程非常完美,有没有办法将代码图像更改移动到函数中?因为我希望有一组按钮,代码是分开的(理想情况下是在单独的.kt文件中)。i、 e.private fun changeimageelement1(imageButtonX:Int){imageButton1.setImageResource(R.drawable.greenbutton)}