在开发中我们常常会根据项目的整体样式调整EditText的边框颜色,选中和未选中颜色。
首先定义两个drawable文件,选中是的边框样式和未选中时的边框样式,代码如下:
首先定义两个drawable文件,选中是的边框样式和未选中时的边框样式,代码如下:
选中时:edittext_focus.xml
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" >
<!-- 边缘线的宽度和颜色 -->
<stroke
android:width="1px"
android:color="#1cc4ad" />
<!-- 中间渐变,角度0从左往右,正值为逆时针,270度为从上到下 -->
<gradient
android:angle="270"
android:centerColor="#ffffff"
android:endColor="#ffffff"
android:startColor="#ffffff" />
<!-- 设置padding -->
<padding
android:bottom="10dp"
android:left="10dp"
android:right="10dp"
android:top="10dp" />
</shape>
未选中时:edittext_normal.xml
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" >
<!-- 边缘线的宽度和颜色 -->
<stroke
android:width="1px"
android:color="#66cccccc" />
<!-- 中间渐变,角度0从左往右,正值为逆时针,270度为从上到下 -->
<gradient
android:angle="270"
android:centerColor="#ffffff"
android:endColor="#ffffff"
android:startColor="#ffffff" />
<!-- 设置padding -->
<padding
android:bottom="10dp"
android:left="10dp"
android:right="10dp"
android:top="10dp" />
</shape>
然后,定义selector文件,代码如下:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="@drawable/edittext_normal" android:state_window_focused="false"/>
<item android:drawable="@drawable/edittext_focus" android:state_focused="true"/>
</selector>
最后,在EditText中引用,设置为背景即可,代码如下:
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@drawable/edittext_selector"
/>
效果图: