problem:
Sometimes we need to set a click effect for the button when laying out, that is, the default is a color, and the finger is put on it is another color. This effect can be done as follows:
1. This is the layout of the button
<RelativeLayout
android:layout_width="155dp"
android:layout_height="53dp"
android:layout_gravity="center_horizontal"
android:layout_marginBottom="27dp"
android:background="@drawable/btn_common"
android:onClick="startAnswer">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:text="开始测试"
android:textColor="#FFFFFF"
android:textSize="19sp" />
</RelativeLayout>
In the background file of the layout, we write:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="@drawable/btn_color_bg_hover" android:state_focused="true" /><!--点击状态是颜色-->
<item android:drawable="@drawable/btn_color_bg_hover" android:state_pressed="true" /><!--默认颜色-->
<item android:drawable="@drawable/btn_color_bg" />
</selector><!--触摸状态时颜色-->
The content of btn_color_bg_hover.xml is as follows:
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<solid android:color="#FFFFFF" />
<!-- 设置圆角 -->
<corners android:radius="23dp" />
<!-- 设置边框 -->
<stroke
android:width="1px"
android:color="#efefef" />
<!--left to right-->
<gradient
android:angle="45"
android:endColor="#6ba0fe"
android:startColor="#44e8ff" />
</shape>
The content of btn_color_bg.xml is as follows:
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<solid android:color="#FFFFFF" />
<!-- 设置圆角 -->
<corners android:radius="23dp" />
<!-- 设置边框 -->
<stroke
android:width="1px"
android:color="#efefef" />
<!--left to right-->
<gradient
android:angle="45"
android:endColor="#5489e7"
android:startColor="#2cc9df" />
</shape>
In this way, when we click, we separate the styles of the two layout files