How to use SearchView.OnQueryTextListener() in searchable spinner?

有些话、适合烂在心里 提交于 2019-12-01 16:34:54

Instead of using a Spinner with SearchView, I would suggest you to achieve this with ListView and SearchView, I tried and it works very well.

Put a button on your activity. Now clicking on this button will open a custom dialog.

Your custom_dialog.xml

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

    <android.support.v7.widget.SearchView
        android:id="@+id/searchView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

    <ListView
        android:id="@+id/listView"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent" />

</LinearLayout>

Then set your button onClick event and do the following.

 @Override
            public void onClick(View view) {
                Dialog dialog = new Dialog(SearchText.this);
                LayoutInflater inflater = LayoutInflater.from(SearchText.this);
                View view1 = inflater.inflate(R.layout.custom_search_layout, null);
                ListView listView = view1.findViewById(R.id.listView);
                SearchView searchView = view1.findViewById(R.id.searchView);

                final ArrayAdapter<String> stringArrayAdapter = new ArrayAdapter<String>(SearchText.this, android.R.layout.simple_list_item_1, getResources().getStringArray(R.array.my_currency));
                listView.setAdapter(stringArrayAdapter);

                searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
                    @Override
                    public boolean onQueryTextSubmit(String newText) {
                        return false;
                    }

                    @Override
                    public boolean onQueryTextChange(String newText) {
                        stringArrayAdapter.getFilter().filter(newText);
                        return false;
                    }
                });
                dialog.setContentView(view1);
                dialog.show();
            }

Now do your search, and add OnItemClickListener on your listview, and do whatever you want after selecting your choice.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!