我的 Activity 中有一个按钮,我希望它具有我的主题的强调色。
与其像之前的 Lollipop 一样制作我自己的可绘制对象,我自然更愿意使用新的 backgroundTint
属性。
<Button
android:id="@+id/btnAddCode"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:backgroundTint="@color/accent"
android:text="@string/addressInfo_edit_addCode" />
不幸的是它没有效果,按钮保持灰色。
我为 backgroundTintMode
尝试了不同的值,但没有任何改变。
我还尝试在我的 Activity 中以编程方式执行此操作,但没有任何改变。
addCodeView.findViewById(R.id.btnAddCode).setBackgroundTintList(
getResources().getColorStateList(R.color.accent));
为什么我的色调会被忽略?
编辑: 澄清一下,我确实在 Lollipop 设备上进行测试。 其他小部件(例如 EditText)已正确自动着色。
最佳答案
坏消息
正如 BoD 所说,在 Lollipop 5.0(API 级别 21)中为 Button 的背景着色是没有意义的。
好消息
Lollipop 5.1(API 级别 22)似乎通过更改 btn_mtrl_default_shape.xml(以及其他文件)解决了这个问题:https://android.googlesource.com/platform/frameworks/base/+/6dfa60f33ca6018959ebff1efde82db7d2aed1e3%5E!/#F0
好消息
新的支持库(版本 22.1+)adds backward-compatible tinting support很多组件,包括AppCompatButton !
不幸的是, android:backgroundTint
属性仍然不起作用(也许我做错了什么)——所以你必须在代码中设置 ColorStateList
,使用 setSupportBackgroundTintList()
.很高兴看到将来支持 android:backgroundTint
。 更新:Marcio Granzotto 评论说 app:backgroundTint
适用于 AppCompatButton!请注意,它是 app:
,而不是 android:
,因为它在 app/library 中。
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<AppCompatButton
android:id="@+id/mybutton"
android:layout_width="wrap_content" android:layout_height="wrap_content"
android:text="Testing, testing"
app:backgroundTint="#ff00ff"/>
</LinearLayout>
如果你让它继承自 AppCompatActivity
,你的 Activity 将自动膨胀一个 AppCompatButton
而不是普通的 Button
。
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
AppCompatButton v = (AppCompatButton) findViewById(R.id.mybutton);
ColorStateList csl = new ColorStateList(new int[][]{new int[0]}, new int[]{0xffffcc00});
v.setSupportBackgroundTintList(csl);
}
}
您当然应该从颜色资源中获取 ColorStateList
,但我很懒,所以...
哦,别忘了让你的应用主题基于 Theme.AppCompat
主题之一,否则兼容 View 会非常非常难过... ;)
这适用于 2.3.7( Gingerbread MR1)和 5.0( Lollipop “经典”)。
关于android - Lollipop 的 backgroundTint 对 Button 没有影响,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27735890/