转载:https://www.jianshu.com/p/02f8774de6f2(原文自定义Button)
在Android开发中,按钮是最经常使用的控件,按钮所涉及的样式无非几种
- 边框
- 圆角
- 按下的颜色
现在有一个按钮的需求如下:
1.背景颜色: 正常: #ff0000 按下: #008888
2.文字颜色:正常: #ffffff 按下: #000000
3.圆角:弧度为5dp
4.边框:宽度:2px 颜色:#000000
1. selector+shape
- 编写背景selector+shape
//正常shape normal.xml
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
<corners android:radius="5dp" />
<stroke
android:width="2px"
android:color="#000000" />
<solid android:color="#ff0000" />
</shape>
//按下shape press.xml
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
<corners android:radius="10dp" />
<stroke
android:width="2px"
android:color="#000000" />
<solid android:color="#008888" />
</shape>
//selector
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="@drawable/normal" android:state_pressed="false" />
<item android:drawable="@drawable/press" android:state_pressed="true" />
</selector>
- 编写文字颜色selector
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:color="#ffffff" android:state_pressed="false" />
<item android:color="#000000" android:state_pressed="true" />
</selector>
- 在layout文件中使用
<TextView
android:layout_width="match_parent"
android:layout_height="40dp"
android:layout_margin="20dp"
android:background="@drawable/bgc_btn"
android:clickable="true"
android:gravity="center"
android:text="selector+shape方式"
android:textColor="@drawable/color_text" />
- 效果