2

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

3 Answers3

1

This is the way to change background programmatically :

button.backgroundTintList = ContextCompat.getColorStateList(this, R.color.yourColor)
Berkay Kireçci
  • 651
  • 5
  • 18
1
<?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;
        }
    }
0

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))
        }
milan pithadia
  • 840
  • 11
  • 16