首页 > 解决方案 > Android Button setOnClickListener 调用函数更改按钮图像

问题描述

我有一个带有多个按钮的应用程序,图像会根据不同的要求和变量而变化。但是,我无法让图像按钮更改在函数内工作。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>

标签: androidkotlin

解决方案


ClickListener method should besetOnClickListener not setOnClickListener

A sample code:

 button.setOnClickListener{
    counter++
    textView.text = "Click counter : $counter"
 }

Check this tutorial


推荐阅读