How can I change the background of a button programmatically with Android using Kotlin?
            Asked
            
        
        
            Active
            
        
            Viewed 690 times
        
    2
            
            
        - 
                    Same way you do with Java: https://stackoverflow.com/questions/13842447/android-set-button-background-programmatically – Shlomi Katriel Mar 02 '21 at 12:19
- 
                    try this button.setBackgroundColor(resources.getColor(R.color.my_color)) – behrad Mar 02 '21 at 12:20
3 Answers
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;
        }
    }
 
    
    
        Chirag Rathod
        
- 167
- 5
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
