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