安卓学习第30课——SearchView

<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" >

    <SearchView
        android:id="@+id/searchView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" >
    </SearchView>

    <ListView
        android:id="@+id/listView1"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1" >
    </ListView>

</LinearLayout>
package com.example.searchview;

import android.app.Activity;
import android.os.Bundle;
import android.text.TextUtils;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.SearchView;
import android.widget.SearchView.OnQueryTextListener;
import android.widget.Toast;

public class MainActivity extends Activity implements OnQueryTextListener {

    private SearchView sv;
    private ListView lv;
    private final String[] mStrings={"aaaaa","bbbbbb","cccccc"};
    @Override 
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        lv=(ListView) findViewById(R.id.listView1);
        lv.setAdapter(new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,mStrings));
        lv.setTextFilterEnabled(true);
        sv=(SearchView) findViewById(R.id.searchView1);
        sv.setIconifiedByDefault(false);
        sv.setOnQueryTextListener(this);
        sv.setSubmitButtonEnabled(true);
        sv.setQueryHint("查找");
    
    }
    @Override
    public boolean onQueryTextSubmit(String query) {
        Toast.makeText(this,"您的选择是:"+query, Toast.LENGTH_SHORT).show();
        return false;
    }
    @Override
    public boolean onQueryTextChange(String newText) {
        if(TextUtils.isEmpty(newText)){
        lv.clearTextFilter();
    }else{
        lv.setFilterText(newText);
    }
    
        return true;
    }

    
}
使用了OnQueryTextListener 接口。

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。