坏消息
正如 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+ 版)为许多组件添加了向后兼容的着色支持,包括AppCompatButton!
不幸的是,该android:backgroundTint
属性仍然不起作用(也许我做错了什么)——所以你必须设置ColorStateList
in 代码,使用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>
如果你让它继承AppCompatButton
自.Button
AppCompatActivity
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
主题上,否则兼容的视图会非常非常难过... ;)
这适用于 2.3.7(Gingerbread MR1)和 5.0(Lollipop 'Classic')。