searchview与listview的结合使用

package com.example.searchview2; 
 
import android.os.Bundle; 
import android.app.Activity; 
import android.text.TextUtils; 
import android.view.Menu; 
import android.widget.ArrayAdapter; 
import android.widget.ListView; 
import android.widget.SearchView; 
import android.widget.TextView; 
 
public class MainActivity extends Activity implements SearchView.OnQueryTextListener{ 
    ListView listView; 
    SearchView searchView; 
    String[] names; 
    ArrayAdapter adapter; 
    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
        super.onCreate(savedInstanceState); 
        setContentView(R.layout.activity_main); 
        names=new String[]{"aa","ddf","qw","sd","fd","as","cf","re","fg"}; 
        listView=(ListView) findViewById(R.id.list); 
        searchView=(SearchView) findViewById(R.id.searchView); 
         //Note that the Adapter used by this view must implement the Filterable interface. 
        listView.setAdapter(adapter=new ArrayAdapter(getApplicationContext(), android.R.layout.simple_expandable_list_item_1,names)); 
        //设置当在搜索栏里输入内容时,内容在一个小框框中显示(类似textview),若没有这行代码则没有这样的效果 
        listView.setTextFilterEnabled(true); 
        //setIconifiedByDefault为true时,searchview不是展开的,当为false时searchview一开始就是展开的 
        searchView.setIconifiedByDefault(true); 
        searchView.setOnQueryTextListener(this); 
        searchView.setSubmitButtonEnabled(false); 
        searchView.setQueryHint("INPUT"); 
         
    } 
 
    @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 onQueryTextChange(String newText) { 
        // TODO Auto-generated method stub 
        //TextUtils.isEmpty(string)判断()里面string是否为空,或者为0字节 
        //若为空或0字节则返回false,否则为true 
        if (TextUtils.isEmpty(newText)) { 
            //Clear the text filter. 
            listView.clearTextFilter(); 
        }else { 
            //Sets the initial value for the text filter. 
            listView.setFilterText(newText.toString()); 
        } 
        return false; 
    } 
 
    @Override 
    public boolean onQueryTextSubmit(String query) { 
        // TODO Auto-generated method stub 
        return false; 
    } 
 
}

你可能感兴趣的:(android开发)