坏消息
正如 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:,因为它在应用程序/库中。
<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,你的活动将自动膨胀一个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 主题之一上,否则compat 视图会非常非常难过... ;)
这适用于 2.3.7(姜饼 MR1)和 5.0(棒棒糖“经典”)。