Search code examples
androidandroidx

AndroidX Setting Background Color on Button has NO Effect


I usually set the background color on a button simply in XML using android:background or programatically using setBackgroundColor but now with the AndroidX library (i assume...), these has no effect on the button color

it seems that setting android:backgroundTint is working but this works only for APIs 21 and above

how can i achieve this ?

example:

Shouldnt this produce a layout with a red backgrounded button...

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              android:orientation="vertical"
              android:layout_width="match_parent"
              android:layout_height="match_parent">

    <Button android:layout_width="wrap_content" android:layout_height="wrap_content"
    android:background="#af2222"/>

</LinearLayout>

Solution

  • As svkaka's answer mentioned, i used app:backgroundTint="#af2222" in xml to solve the issue.

    Programatically, i used this:

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) statusButton.backgroundTintList = ColorStateList.valueOf(MY_COLOR)
    
    else  statusButton.setBackgroundColor(MY_COLOR)
    

    Also to note, this is required on Both material and support design button since the android:background="#fff" on both now seems to have no effect