android 搜索框实现方法,还在手写搜索框?out了!附加Toast及时改变内容

效果图:

这里写图片描述

教程::

如图,之前用到搜索框都是自己写,里面的EditText还得设置内容改变监听来实现实时搜索,偶然间发现V7包中存在有搜索控件

<android.support.v7.widget.SearchView
    android:id="@+id/searchview"
    android:layout_width="match_parent"
    android:layout_height="56dp"
    android:focusable="false"
    android:focusableInTouchMode="false"
    android:background="@drawable/seatch_bj" //控件整体的背景
    app:iconifiedByDefault="false"
    app:queryBackground="@drawable/seatch_et_bj"  //搜索框的背景
    app:queryHint="请输入关键字"
    android:textColor="#000000"/>

然后设置个监听就OK啦:


searchview = (SearchView) findViewById(R.id.searchview);

searchview.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
    @Override
    public boolean onQueryTextSubmit(String query) {
        return false;
    }

    //搜索框内部改变回调,newText就是搜索框里的内容
    @Override
    public boolean onQueryTextChange(String newText) {
        thisToast(newText);    //这里面就是一个Toast
        return true;
    }
});

搜索框也可以根据自己的爱好自行定义,比如背景:

这里写图片描述

不知这些,还有很多自定义的属性可以设置,例如:

这里写图片描述

有上图可以看出,有内边距啊、搜索图标啊……都可以根据自己想要的自行定义,好了,就这些,由于代码比较简单,就不放源码了

拓展:平常用的Toast一般都是2秒才能显示下一条Toast,而动态图中的Toast可以随时更改内容,实现起来比较简单:

private Toast toast;


private void thisToast(final String msg){
    if(toast == null){
        toast = Toast.makeText(MainActivity.this, msg, Toast.LENGTH_SHORT);
    }
    toast.setText(msg);
    toast.show();
    }

猜你喜欢

转载自blog.csdn.net/fan7983377/article/details/52174866