- 在res/drawable目录下新建按钮样式文件 btn_normal.xml(正常状态) 和 btn_pressed.xml(按下状态)。
btn_normal.xml文件:
<?xml version="1.0" encoding="utf-8"?>
<shape
xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<!-- 圆角的半径 -->
<corners android:radius="10dp"/>
<!-- 填充颜色 -->
<solid android:color="#3a8fea"/>
</shape>
btn_pressed.xml文件:
<?xml version="1.0" encoding="utf-8"?>
<shape
xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<!-- 圆角的半径 -->
<corners android:radius="10dp"/>
<!-- 填充颜色 -->
<solid android:color="#0662f5"/>
</shape>
2.在res/drawable目录下新建样式文件 btn_selector.xml 文件,定义按钮的不同状态样式。
btn_selector.xml文件:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<!-- 正常状态 -->
<item android:drawable="@drawable/btn_normal" android:state_pressed="false"/>
<!-- 按下状态 -->
<item android:drawable="@drawable/btn_pressed" android:state_pressed="true"/>
</selector>
3.使用按钮样式。
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".ButtonActivity">
<Button
android:id="@+id/btn1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="30dp"
android:layout_marginStart="30dp"
android:text="button"
android:textColor="#fff"
android:background="@drawable/btn_selector"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</android.support.constraint.ConstraintLayout>