Android Kotlin - Changing the background of a button programmatically

Viewed 369

How can I change the background of a button programmatically with Android using Kotlin?

3 Answers

This is the way to change background programmatically :

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>

create drawable in /app/src/main/res/drawable/btn_drawable.xml
and set it as background of button.
button.setBackgroundResource(R.drawable.btn_drawable);

Change background on button click :

button.setOnClickListener {
        if(isThemeOne){
            button.setBackgroundResource(R.drawable.btn_drawable_1);
            isThemeOne=false;
        } else {
            button.setBackgroundResource(R.drawable.btn_drawable_2);
            isThemeOne=true;
        }
    }

try this easy way for all version

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