android - 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>
解决方案
ClickListener method should besetOnClickListener
not setOnClickListener
A sample code:
button.setOnClickListener{
counter++
textView.text = "Click counter : $counter"
}
Check this tutorial
推荐阅读
- php - 使用开始日期 PHP 每周返回结果
- google-chrome - Opensearch - 更改搜索引擎的名称
- keras - 使用 Keras 进行预测。我不断收到错误消息
- rabbitmq - SSH、RabbitMQ、协议“inet_tcp”:注册/监听错误:econnrefused
- .net - CultureInfo.GetCultures 为特定文化返回不同的 DateTimeSettings,而不是按名称或 LCID 使用 GetCultureInfo
- html.textboxfor - 想知道C#.Dot net MVC Helper Class css文件位置
- asp.net - 如何在本地使用 sharePoint 做一个公共站点
- c# - ASP.Net Core 应用程序中的成员资格提供程序
- bootstrap-4 - Bootstrap 4 卡片组中的固定数量的卡片
- javascript - ant design - “取消”和“X”关闭按钮上的模态值重置 - API RESPONSE BASE REACT JS