简体   繁体   中英

Android ActionBar with searchView

How to add search functionality in action bar which can be a search specific listview from any activity of the app?

I am unable to find any proper example. The list view data comes from server, and was implemented with the help of this link .

first of all you need to implement Filterable to your Adapter. Then add search field to your actionbar menu.

<item android:id="@+id/menu_search" android:icon="@android:drawable/ic_menu_search" app:showAsAction="always" app:actionViewClass="android.support.v7.widget.SearchView" android:title="Search"/>

after this do the following in your activity.

@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        MenuItem searchMenuItem = menu.findItem(R.id.menu_search);
        if (searchMenuItem == null) {
            return;
        }

        searchView = (SearchView) searchMenuItem.getActionView();
        if (searchView != null) {
            searchView.setQueryHint(getString(R.string.search_hint));
            searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
                @Override
                public boolean onQueryTextSubmit(String s) {
                    return false;
                }

                @Override
                public boolean onQueryTextChange(String s) {
                    SearchFragment.this.onQueryTextChange(s);
                    return false;
                }
            });
        }
    }

and then

void onQueryTextChange(String query) { searchAdapter.getFilter().filter(query); }

To implement a basic searchView using toolbar in android, roughly, you need to make the following modifications to the customListVolley project:

1. Add a toolbar to your activity_main.xml
For example :

<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity" >

    <android.support.v7.widget.Toolbar
        android:visibility="visible"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        android:id="@+id/toolbar"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:background="#1111DD"
        app:theme="@style/ToolbarTheme"/>

    <ListView
        android:id="@+id/list"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:divider="@color/list_divider"
        android:dividerHeight="1dp"
        android:listSelector="@drawable/list_row_selector" />

</LinearLayout>


2. Create search_toolbar.xml & add it under menu folder
Like this:

<menu
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools" >

    <item
        android:id="@+id/action_search"
        android:icon="@android:drawable/ic_menu_search"
        app:showAsAction="always"
        app:actionViewClass="android.support.v7.widget.SearchView"
        android:title="Search"
        /> 

</menu>


3. Make your CustomListAdapter.java implement Filterable
For example:

public class CustomListAdapter
        extends BaseAdapter
    implements Filterable
{
    private Activity activity;
    private LayoutInflater inflater;
    private List<Movie> movieItems;
    private List<Movie> originalList; //<--

    //-->
    private ItemFilter mFilter = new ItemFilter();

    @Override
    public Filter getFilter() {
        return mFilter;
    }
    //<--

    ImageLoader imageLoader = AppController.getInstance().getImageLoader();

    public CustomListAdapter(Activity activity, List<Movie> movieItems) {
        this.activity = activity;
        this.movieItems = movieItems;
        originalList = movieItems; //<--
    }

    .
    .
    .

    //-->Implement your filter logic
    private class ItemFilter extends Filter {
        @Override
        protected FilterResults performFiltering(CharSequence constraint) {

            String filterString = constraint.toString().toLowerCase();

            FilterResults results = new FilterResults();

            List<Movie> movies = new ArrayList<>();

            for(Movie item : originalList)
            {
                if(item.getTitle().toLowerCase().contains(filterString))
                    movies.add(item);
            }

            movieItems = movies;
            results.count = movies.size();
            return null;
        }

        @SuppressWarnings("unchecked")
        @Override
        protected void publishResults(CharSequence constraint, FilterResults results) {
            notifyDataSetChanged();
        }
    }//<--
}

4. Initialize the toolbar & the searchView in you main activity
Like this:

public class MainActivity extends AppCompatActivity {
    // Log tag
    private static final String TAG = MainActivity.class.getSimpleName();

    // Movies json url
    private static final String url = "http://api.androidhive.info/json/movies.json";
    private ProgressDialog pDialog;
    private List<Movie> movieList = new ArrayList<Movie>();
    private ListView listView;
    private CustomListAdapter adapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        //-->Setup your toolbar
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        .
        . 
        .
    }

    .
    .
    .


    //--->Setup your searchView
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.search_toolbar, menu);
        MenuItem searchItem = menu.findItem(R.id.action_search);

        SearchView.OnQueryTextListener textChangeListener = new SearchView.OnQueryTextListener()
        {
            @Override
            public boolean onQueryTextChange(String newText)
            {
                // this is your adapter that will be filtered
                adapter.getFilter().filter(newText);
                return true;
            }
            @Override
            public boolean onQueryTextSubmit(String query)
            {
                // this is your adapter that will be filtered
                adapter.getFilter().filter(query);
                return true;
            }
        };
        SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);

        SearchView searchView = null;
        if (searchItem != null) {
            searchView = (SearchView) searchItem.getActionView();
        }
        if (searchView != null) {
            searchView.setSearchableInfo(searchManager.getSearchableInfo(getComponentName()));
            searchView.setIconifiedByDefault(false);
            searchView.setOnQueryTextListener(textChangeListener);
        }

        return super.onCreateOptionsMenu(menu);
//        return true;
    }
}

This should allow you to implement a basic searchView.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM