我使用以下代码更改了浮动操作按钮backgroundTintList颜色:
- fab.setBackgroundTintList(ColorStateList.valueOf(mResources.getColor(R.color.fab_color)));
但我最终在API 4.4.2上得到以下内容:
在API 21上的一切看起来都很好< =但是在API 21之下的任何东西,我对FAB都有这个问题. 我是以编程方式创建FAB,如下所示:
- FloatingActionButton fab = new FloatingActionButton(this);
- CoordinatorLayout.LayoutParams layoutParams = new CoordinatorLayout.LayoutParams(
- ViewGroup.LayoutParams.WRAP_CONTENT,ViewGroup.LayoutParams.WRAP_CONTENT);
- fab.setLayoutParams(layoutParams);
- layoutParams.rightMargin = mResources.getDimensionPixelSize(R.dimen.activity_horizontal_margin);
- ((CoordinatorLayout) findViewById(R.id.coordinatorLayout)).addView(fab);
- CoordinatorLayout.LayoutParams p = (CoordinatorLayout.LayoutParams) fab.getLayoutParams();
- p.setAnchorId(R.id.appBarLayout);
- p.anchorGravity = Gravity.BOTTOM | Gravity.END;
- fab.setLayoutParams(p);
- fab.setVisibility(View.VISIBLE);
- fab.setBackgroundTintList(ColorStateList.valueOf(mResources.getColor(R.color.fab_color)));
- fab.setImageDrawable(getResources().getDrawable(R.drawable.ic_button));
我也碰巧在FloatingActionButton的官方source code上运行,我看到他们在这里实例化borderDrawable:
- @Override
- void setBackgroundDrawable(Drawable originalBackground,ColorStateList backgroundTint,PorterDuff.Mode backgroundTintMode,int rippleColor,int borderWidth) {
- // Now we need to tint the original background with the tint
- mShapeDrawable = DrawableCompat.wrap(originalBackground.mutate());
- DrawableCompat.setTintList(mShapeDrawable,backgroundTint);
- if (backgroundTintMode != null) {
- DrawableCompat.setTintMode(mShapeDrawable,backgroundTintMode);
- }
- final Drawable rippleContent;
- if (borderWidth > 0) { // BORDER DRAWABLE RIGHT HERE!!
- mBorderDrawable = createBorderDrawable(borderWidth,backgroundTint);
- rippleContent = new LayerDrawable(new Drawable[]{mBorderDrawable,mShapeDrawable});
- } else {
- mBorderDrawable = null;
- rippleContent = mShapeDrawable;
- }
- mRippleDrawable = new RippleDrawable(ColorStateList.valueOf(rippleColor),rippleContent,null);
- mShadowViewDelegate.setBackgroundDrawable(mRippleDrawable);
- mShadowViewDelegate.setShadowPadding(0,0);
- }
解决方法
只需更改样式文件中的coloraccent
- <item name="colorAccent">@color/colorAccent</item>
添加你想要的颜色作为FAB的背景颜色
编辑:okk ..这里是你可以做的另一种选择..在你的xml中定义这个FAB
- <android.support.design.widget.FloatingActionButton
- android:id="@+id/fab"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:layout_gravity="bottom|end"
- app:backgroundTint="@color/fab_color"
- android:layout_margin="@dimen/fab_margin"
- android:src="@android:drawable/ic_dialog_email" />
并且它将进行更改,然后您不需要以编程方式执行.