EditText自定义边框

时间:2022-03-10 00:39:11

1、EditText代码如下 (View代替EditText获取焦点):

<View
    android:focusable="true"
    android:focusableInTouchMode="true"
    android:layout_width="0px"
    android:layout_height="0px"
    />
<EditText
    android:id="@+id/ask_review_message"
    android:layout_width="match_parent"
    android:layout_height="200dp"
    android:padding="10dp"
    android:hint="@string/ask_messageHint"
    android:gravity="top"
    android:background="@drawable/bg_edit_text"
    />

2、bg_edit_text.xml

<?xml version="1.0" encoding="UTF-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_selected="true" android:drawable="@drawable/bg_edit_text_focused" />
    <item android:state_focused="true" android:drawable="@drawable/bg_edit_text_focused" />
    <item android:drawable="@drawable/bg_edit_text_normal" />
</selector> 

3、bg_edit_text_normal.xml

<?xml version="1.0" encoding="UTF-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
    <solid android:color="#FFFFFF" />
    <corners android:radius="3dip"/>
    <stroke
        android:width="1dip"
        android:color="#BDC7D8" />
</shape>  

4、bg_edit_text_focused.xml

<?xml version="1.0" encoding="UTF-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
    <solid android:color="#FFFFFF" />
    <corners android:radius="3dip"/>
    <stroke
        android:width="1dip"
        android:color="#32CD32" />
</shape>  

其实有时候只要一个文件就可以搞定

代码如下:

<?xml version="1.0" encoding="UTF-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">

    <item android:state_pressed="true">
        <shape>
            <solid android:color="#FFFFFF" />

            <corners android:radius="3dip" />

            <stroke android:width="1dip" android:color="#32CD32" />
        </shape>
    </item>
    <item android:state_focused="true">
        <shape>
            <solid android:color="#FFFFFF" />

            <corners android:radius="3dip" />

            <stroke android:width="1dip" android:color="#32CD32" />
        </shape>
    </item>
    <item>
        <shape>
            <solid android:color="#FFFFFF" />

            <corners android:radius="3dip" />

            <stroke android:width="1dip" android:color="#BDC7D8" />
    </shape>
  </item>
</selector>