【发布时间】:2021-03-02 12:16:49
【问题描述】:
如何使用 Kotlin 在 Android 中以编程方式更改按钮的背景?
【问题讨论】:
-
与 Java 相同:stackoverflow.com/questions/13842447/…
-
试试这个 button.setBackgroundColor(resources.getColor(R.color.my_color))
如何使用 Kotlin 在 Android 中以编程方式更改按钮的背景?
【问题讨论】:
这是以编程方式更改背景的方法:
button.backgroundTintList = ContextCompat.getColorStateList(this, R.color.yourColor)
【讨论】:
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
/// write your custome code here...
</shape>
在/app/src/main/res/drawable/btn_drawable.xml中创建drawable
并将其设置为按钮的背景。
button.setBackgroundResource(R.drawable.btn_drawable);
点击按钮改变背景:
button.setOnClickListener {
if(isThemeOne){
button.setBackgroundResource(R.drawable.btn_drawable_1);
isThemeOne=false;
} else {
button.setBackgroundResource(R.drawable.btn_drawable_2);
isThemeOne=true;
}
}
【讨论】:
为所有版本尝试这种简单的方法
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.M) {
btn.setBackgroundColor(getColor(R.color.black))
}else{
btn.setBackgroundColor(resources.getColor(R.color.black))
}
【讨论】: