版權聲明:本文爲xing_star原創文章,轉載請註明出處!java
本文同步自http://javaexception.com/archives/186android
FloatingActionButton 動態更換背景色
最近碰到了個需求場景,須要動態切換FloatingActionButton的背景色
先看下xml中的佈局
<android.support.design.widget.FloatingActionButton android:id=」@+id/fab_main_circle」 android:layout_width=」wrap_content」 android:layout_height=」wrap_content」 android:src=」@drawable/ic_photo_album_white_48dp」 app:fabSize=」normal」 app:backgroundTint=」@color/colorPrimaryDark」/>
FloatingActionButton的圖片源是ic_photo_album_white_48dp ,這是一張純色的圖片,圖片沒有背景色,須要經過app:backgroundTint設置背景色。
當咱們的需求出現動態更改背景色時,就會碰到問題.
ColorStateList colorStateList = ContextCompat.getColorStateList(getApplicationContext(), R.color.red); fabDownloadCircle.setBackgroundTintList(colorStateList);
屢次執行這段設置背景色的代碼,會出現更改不了背景色,背景色始終保持在某一特定的色值。非常奇怪。
google了一番,也沒有找到合適的答案。
最終到FloatingActionButton的源碼裏面,找到了一個api,setBackgroundTintMode。問題獲得解決。
完整的代碼以下:
ColorStateList colorStateList = ContextCompat.getColorStateList(getApplicationContext(), R.color.colorPrimaryDark); fabRandomCircle.setBackgroundTintMode(PorterDuff.Mode.SRC_ATOP); fabRandomCircle.setBackgroundTintList(colorStateList);
ColorStateList colorStateList = ContextCompat.getColorStateList(getApplicationContext(), R.color.red; fabRandomCircle.setBackgroundTintMode(PorterDuff.Mode.SRC_ATOP); fabRandomCircle.setBackgroundTintList(colorStateList);