FloatingActionButton動態更換背景色


版權聲明:本文為xing_star原創文章,轉載請注明出處!

本文同步自http://javaexception.com/archives/186

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);
 
 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM