需求
最近项目里需要一个搜索框,其需求是这样的:当用户输入字符,将自动进行搜索,且搜索框中有字符时,显示一个删除icon,点击可以清空输入框。
分析
在这两个功能我们都需要监听EditText中输入字符的变化
1. 自动搜索:
这里我们可以采用接口回调的机制来完成。
2. 清空按钮:
首先判断EditText中的字符长度,如果字符的长度大于0且有焦点的时候让图标显示。
代码
- 布局文件 activity_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.dd.test.MainActivity" >
<com.dd.test.AutoSearchClearEditText
android:id="@+id/et"
android:layout_width="match_parent"
android:layout_height="40dp"
android:layout_centerInParent="true"
android:layout_margin="5dp"
android:drawableRight="@drawable/delete"
android:padding="2dp" />
</RelativeLayout>
布局文件很简单,添加一个自定义的EditText,让其居中显示。其中android:drawleRight=”@drawable/delete”这里是为EditText的右侧显示一张清空图标。
- MainActivity.class
public class MainActivity extends Activity implements OnAutoSearchListener {
@Override