要设置button的颜色,可以使用以下方法:
<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button"
android:background="@color/colorPrimary" />
Button button = findViewById(R.id.button);
button.setBackgroundColor(ContextCompat.getColor(this, R.color.colorPrimary));
在res/drawable文件夹下创建一个selector文件,比如button_selector.xml:
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_pressed="true" android:drawable="@color/colorPrimaryDark" /> <!-- pressed -->
<item android:state_focused="true" android:drawable="@color/colorAccent" /> <!-- focused -->
<item android:drawable="@color/colorPrimary" /> <!-- default -->
</selector>
然后在xml布局文件中设置button的背景为该selector文件:
<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button"
android:background="@drawable/button_selector" />