Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android setBackgroundTintList on pre-lollipop devices

I'm working with FloatingActionButton. The user should be able to switch the FAB background color within a onClick Event.

However, the recommended call to setBackgroundTintList seems to be only compatible from 21+ API.

How do I - correctly - go about it on pre-lollipop devices? Is there any alternative I could use?

Thanks in advance.

like image 517
Matteo Avatar asked Nov 10 '15 20:11

Matteo


1 Answers

You can use also setSupportBackgroundTintList

Applies a tint to the background drawable. Does not modify the current tint mode, which is SRC_IN by default.

Subsequent calls to View.setBackground(Drawable) will automatically mutate the drawable and apply the specified tint and tint mode.

Also take a look on ViewCompat.setBackgroundTintList()

Applies a tint to the background drawable.

This will always take effect when running on API v21 or newer. When running on platforms previous to API v21, it will only take effect if view implement the TintableBackgroundView interface.

I found a solution here on SO that I've used before and is this:

public static void setButtonTint(Button button, ColorStateList tint) {
  if (Build.VERSION.SDK_INT == Build.VERSION_CODES.LOLLIPOP && button instanceof AppCompatButton) {
      ((AppCompatButton) button).setSupportBackgroundTintList(tint);
  } else {
      ViewCompat.setBackgroundTintList(button, tint);
  }
}

It works for me I hope it works for you too.

like image 73
Skizo-ozᴉʞS Avatar answered Oct 06 '22 02:10

Skizo-ozᴉʞS