我有一个带有多个按钮的应用程序,图像会根据不同的要求和变量而变化。但是,我无法使图像按钮更改在功能内起作用。 setOnClickListner将设置函数调用,并且在函数内将更改按钮内的图像。
如何更改按钮中的图像?
MainActivity.kt
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>
答案 0 :(得分:2)
ClickListener方法应为filterM p = go
where
go [] = pure []
go (x : xs) = do
px <- p x
-- Or: if px then (x :) <$> go xs else go xs
xs' <- go xs
pure (if px then x : xs' else xs')
,而不是setOnClickListener
示例代码:
setOnClickListener
查看this教程
答案 1 :(得分:2)
您不应在setOnClickListener之后使用(),而应使用
button.setOnClickLisener{
//your actions go here
}