SearchView搜索框控件简单使用

配合listview可以达到搜索显示下拉列表的目的

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    >

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

    </SearchView>

    <ListView
        android:id="@+id/lv"
        android:layout_width="match_parent"
        android:layout_height="300dp"
        >
    </ListView>


</LinearLayout>
public class MainActivity extends AppCompatActivity {
    private ListView listView;
    private SearchView searchView;

    private final String[] strings = {"aaa","bbb","ccc"};

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        listView = (ListView) findViewById(R.id.lv);
        searchView = (SearchView) findViewById(R.id.sv);


        listView.setAdapter(new ArrayAdapter<String>(this , android.R.layout.simple_dropdown_item_1line , strings));
        //listview启动过滤
        listView.setTextFilterEnabled(true);
        //一开始不显示
        listView.setVisibility(View.GONE);
        //搜索框不自动缩小为一个搜索图标,而是match_parent
        searchView.setIconifiedByDefault(false);
        //显示搜索按钮
        searchView.setSubmitButtonEnabled(true);
        //默认提示文本
        searchView.setQueryHint("查找");

        searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
            //单击搜索按钮的监听
            @Override
            public boolean onQueryTextSubmit(String query) {
                Toast.makeText(MainActivity.this, "123", Toast.LENGTH_SHORT).show();

                return false;
            }
            //输入字符的监听
            @Override
            public boolean onQueryTextChange(String newText) {
                if (TextUtils.isEmpty(newText)){
                    listView.setVisibility(View.GONE);
                    listView.clearTextFilter();
                }
                else {
                    listView.setVisibility(View.VISIBLE);
                    listView.setFilterText(newText);
                }

                return true;
            }
        });

    }
}




阅读更多
上一篇listview的可展开,显示隐藏 item 简单实现
下一篇ScrollView与HorizontalSrollView结合实现可横竖向滑动的界面
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

关闭
关闭
关闭