How to build Gmail like search box in the action b

2019-01-16 13:35发布

I am currently using SearchView widget inside ActionBarcompat to filter a list while searching.

When the user starts entering text the ListView in the main layout updates with an Adapter to filter the results. I do this by implementing a OnQueryTextListener and filter the results on each key stroke.

Instead, I want to create a Gmail like search box with auto suggest list generated and no changes to the underlying view

enter image description here

I have went through this tutorial that uses the SearchView component but it requires a searchable activity. I want the drop-down to be over the MainActivity where I have the ListView (like in the Gmail app) and not a dedicated Activity.
Besides, implementing it the same way as in the tutorial seems like an overkill for what I want (just a dropdown)

7条回答
爷、活的狠高调
2楼-- · 2019-01-16 14:02

I've successfully used Michaels reply (https://stackoverflow.com/a/18894726/2408033) but I didn't like how manual it was, inflating the views and adding it to the actionbar, toggling its state etc.

I modified it to to use an ActionBar ActionView instead of adding the view manually to the actionbar/toolbar.

I find this works a lot better since I don't need to manage the open/close state and hiding of views as he did in his example in the toggleSearch method in the added link. It also works perfectly with the back button.

In my menu.xml

 <item
        android:id="@+id/global_search"
        android:icon="@android:drawable/ic_menu_search"
        android:title="Search"
        app:actionLayout="@layout/actionbar_search"
        app:showAsAction="ifRoom|collapseActionView" />

In my onCreateOptionsMenu

 View actionView = menu.findItem(R.id.global_search).getActionView();
 searchTextView = (ClearableAutoCompleteTextView) actionView.findViewById(R.id.search_box);
 searchTextView.setAdapter(searchAdapter);

You can find a fully working version of the implementation in my project. Note there are two search views as I was using the actual SearchView to filter a listView.

https://github.com/babramovitch/ShambaTimes/blob/master/app/src/main/java/com/shambatimes/schedule/MainActivity.java

查看更多
登录 后发表回答