【问题标题】:Android Kotlin - Changing the background of a button programmaticallyAndroid Kotlin - 以编程方式更改按钮的背景
【发布时间】:2021-03-02 12:16:49
【问题描述】:

如何使用 Kotlin 在 Android 中以编程方式更改按钮的背景?

【问题讨论】:

标签: android kotlin


【解决方案1】:

这是以编程方式更改背景的方法:

button.backgroundTintList = ContextCompat.getColorStateList(this, R.color.yourColor)

【讨论】:

    【解决方案2】:
    <?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;
            }
        }
    

    【讨论】:

      【解决方案3】:

      为所有版本尝试这种简单的方法

      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))
              }
      

      【讨论】:

        猜你喜欢
        • 2011-03-07
        • 2020-05-15
        • 2022-11-02
        • 2013-09-12
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多