首页 > 代码库 > UI复习-组件:SearchView(搜索过滤)

UI复习-组件:SearchView(搜索过滤)

package com.brady.est;import android.annotation.SuppressLint;import android.os.Bundle;import android.support.v7.app.ActionBarActivity;import android.view.Menu;import android.view.MenuItem;import android.widget.ArrayAdapter;import android.widget.ListView;import android.widget.SearchView;import android.widget.Toast;@SuppressLint({ "HandlerLeak", "ClickableViewAccessibility" })public class MainActivity extends ActionBarActivity implements SearchView.OnQueryTextListener{    private String[] keywords = {"fdsaddd","fdaddddd","ccccccccccc","b"};        private ListView listView;    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);                SearchView searchView = (SearchView)findViewById(R.id.searchView);        searchView.setQueryHint("查询");        searchView.setSubmitButtonEnabled(true);        searchView.setOnQueryTextListener(this);        searchView.setIconifiedByDefault(false);                listView = (ListView)findViewById(R.id.list);        listView.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,keywords));        listView.setTextFilterEnabled(true);    }    @Override    public boolean onCreateOptionsMenu(Menu menu) {        // Inflate the menu; this adds items to the action bar if it is present.        getMenuInflater().inflate(R.menu.main, menu);        return true;    }    @Override    public boolean onOptionsItemSelected(MenuItem item) {        // Handle action bar item clicks here. The action bar will        // automatically handle clicks on the Home/Up button, so long        // as you specify a parent activity in AndroidManifest.xml.        int id = item.getItemId();        if (id == R.id.action_settings) {            return true;        }        return super.onOptionsItemSelected(item);    }    @Override    public boolean onQueryTextSubmit(String query) {        Toast.makeText(this, query, 1000).show();        return false;    }    @Override    public boolean onQueryTextChange(String newText) {        listView.setFilterText(newText);        return false;    }}

布局XML文件:

<LinearLayout 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"      android:orientation="vertical"    android:id="@+id/root"    android:padding="5dip"    tools:context="com.brady.est.MainActivity" >            <SearchView         android:layout_width="match_parent"        android:layout_height="wrap_content"        android:id="@+id/searchView"/>    <ListView         android:id="@+id/list"        android:layout_width="match_parent"        android:layout_height="match_parent"/>         </LinearLayout>

界面:

UI复习-组件:SearchView(搜索过滤)