EditText+RecycleView实现搜索功能之一:对EditText内容变化实时监听

搜索功能在某些应用中经常用到,比如一个通讯录App,最近在写一个通讯录的demo,在网上找了很长时间都没有一个好的博客对这一个非常重要的功能做讲解,没办法,自己动手丰衣足食,于是在我的自我探索下找到了一个比较好的实现方法,下面就讲一个非常简洁的demo
首先,实现搜索框有两种方式,一个是使用android.support.v7.widget.SearchView开源包,一个是对EditorText进行改造,对于第一种方法我实在没有学会,我使用的是第二种方法,实际上第二种方法通过自己定制之后感觉比第一种方法还好~
首先看看咱们今天的主角:

<EditText
    android:id="@+id/searchview"
    android:layout_alignParentTop="true"
    android:layout_width="match_parent"
    android:layout_height="50dp"
    android:imeOptions="actionSearch"
    android:hint="请输入关键字"/>

我们可以看到android:imeOptions=”actionSearch”,这样一个属性,这个属性是干什么的呢?这个属性就是用来赋予EditText搜索功能的,记住一定写上!
看看整体布局吧:

<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<EditText
    android:id="@+id/searchview"
    android:layout_alignParentTop="true"
    android:layout_width="match_parent"
    android:layout_height="50dp"
    android:imeOptions="actionSearch"
    android:hint="请输入关键字"/>
<android.support.v7.widget.RecyclerView
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_below="@id/searchview"
    android:id="@+id/ConnectList"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
</android.support.v7.widget.RecyclerView>
</RelativeLayout>

这就是我的界面的布局了。
这样界面部分我们已经完成了,然后我们看看java代码里面怎么写:
首先获取到EditText:

 private EditText etInput;
 etInput=(EditText)findViewById(R.id.searchview);

然后我们需要为EditText设置监听器:

etInput.addTextChangedListener(new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

        }

        @Override
        public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
            Log.d(TAG, "onTextChanged: "+charSequence.toString());
        }

        @Override
        public void afterTextChanged(Editable editable) {

        }
    });

我们在这个监听器里面实现了一个借口TextWatcher,并重写了借口里面的方法,从方法的名字上我们就很容易的看出它的意义,当EditText里面的内容改变的时候就会调用onTextChanged方法,这里面的参数我们只需要关注第一个,这个就是获取到的EditText的内容,这样我们将内容打印出来,就能实现实时监听EditText内容变化的功能了。这样我们可以根据我们应该的不同,在onTextChanged方法里面写不同的搜索逻辑。

[项目源码](https://github.com/MQLX1004/Myhub/tree/master/Connect

  • 4
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值