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<String> 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<String>(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; 
    } 
 
}
相關文章
相關標籤/搜索