在Android

时间:2019-08-25 21:43:16

标签: android user-interface material-design

我正在使用新的材料组件,例如 MaterialButton MaterialCardView
在我的项目中,我需要以编程方式更改材质按钮tintBackground
因此我使用setBackgroundTintList方法来更改色调背景色。

btnOk.setBackgroundTintList(ColorStateList.valueOf(Color.parseColor("#20" + colorAccept)));  
btnOk.setTextColor(Color.parseColor("#" + colorAccept));

如您所见,我正在为材质按钮设置透明颜色。


我在android KitKat 中运行我的应用程序,如您在此图中看到的那样,没有问题。

KitKat OutPut

但是在Android棉花糖中,材质按钮的外观会发生变化,并且在材质按钮下方会出现阴影,如下图所示。

Marshmallow OutPut

我尝试了一些其他代码,但是没有一个起作用。

  • 第一个代码

使用以下代码不会更改android棉花糖中按钮的背景色。

ColorStateList colorOk = new ColorStateList(
                new int[][]{
                        new int[]{R.attr.buttonTint}
                },
                new int[] {
                        Color.parseColor("#20" + colorAccept)
                });  
  • 第二个代码

此代码仅在KitKat中起作用,并且在棉花糖中再次出现阴影!

Drawable buttonDrawable = button.getBackground();
buttonDrawable = DrawableCompat.wrap(buttonDrawable);
//the color is a direct color int and not a color resource
DrawableCompat.setTint(buttonDrawable, Color.RED);
button.setBackground(buttonDrawable);

在较新的API中显示此阴影是什么问题?

2 个答案:

答案 0 :(得分:0)

尝试设置elevation

setElevation(float elevation)

MaterialButton materialButton =findViewById(R.id.buttonid);
materialButton.setElevation(0.0f);

答案 1 :(得分:-1)

此阴影出现在使用 API版本21 更高的设备中。
XML 文件中添加以下属性,使按钮没有阴影。

android:stateListAnimator="@null"
  

属性 stateListAnimator 仅用于 API版本21或更高版本