SearchView--搜索框案例

SearchView--搜索框案例_第1张图片

页面布局content_main.xml


    
    

    


主程序SearchViewTest
package com.eson.searchview ;

import android.os.Bundle ;
import android.support.v7.app.AppCompatActivity ;
import android.text.TextUtils ;
import android.widget.ArrayAdapter ;
import android.widget.ListView ;
import android.widget.SearchView ;
import android.widget.Toast ;

public class SearchViewTest extends AppCompatActivity implements SearchView.OnQueryTextListener {

    private final String[] mString={ "android" ,"html" , "ios", "java" ,"javaScript" , "css", "node.js" };
    private ListView listView ;
    private SearchView searchView ;

    @Override
    protected void onCreate (Bundle savedInstanceState) {
        super .onCreate(savedInstanceState) ;
        setContentView(R.layout. content_main );
        listView = (ListView) findViewById(R.id. listView );
        listView .setAdapter( new ArrayAdapter( this, android.R.layout. simple_list_item_1, mString ));
        listView .setTextFilterEnabled( true) ;

        searchView = (SearchView) findViewById(R.id. searchView );
        //设置该SearchView默认是否自动缩小为图标
        searchView .setIconifiedByDefault( false) ;
        //为该SearchView组件设置事件监听器
        searchView .setOnQueryTextListener( this );
        //设置该SearchView内默认显示的提示文本
        searchView .setQueryHint( "查找" );

    }
   //用户输入字符激发该方法
    @Override
    public boolean onQueryTextSubmit (String query) {
        //实际应用中应该执行该方法内执行实际查询
        //此处仅使用Toast显示用户输入的查询内容
        Toast. makeText( this, "您的选择是:" +query, Toast. LENGTH_SHORT).show() ;
        return false;
    }
   //单击搜索按钮时激发该方法
    @Override
    public boolean onQueryTextChange (String newText) {

        if (TextUtils. isEmpty(newText)){
            //清除ListView的过滤
            listView .clearTextFilter() ;
        } else {
            //使用用户输入的内容对ListView的列表进行过滤
            listView .setFilterText(newText) ;
        }
        return true;
    }
}


你可能感兴趣的:(SearchView--搜索框案例)