Search code examples
androidandroid-layoutandroid-toolbar

place a search button on a fragments toolbar with an intent to an activity


I am trying to add a search icon on my fragment's toolbar. This piece of code and the layout below just adds a menu icon(three vertical dots) on toolbar, and on pressing the menu, I get a search. But I dont want that. I am trying to have a search icon in the toolbar, with an intent to google places autocomplete activity. How I can do that?

Fragment

@Override
public void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setHasOptionsMenu(true);

  @Override
  public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
    inflater.inflate(R.menu.map_menu, menu);
    super.onCreateOptionsMenu(menu, inflater);
  }

map_menu

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:android="http://schemas.android.com/apk/res/android">

    <item
        android:id="@+id/app_bar_search"
        android:icon="@drawable/ic_search_black_24dp"
        android:title="Search"
        app:actionViewClass="android.widget.SearchView"
        android:iconifiedByDefault="true"/>
</menu>

Solution

  • Remove the

        app:actionViewClass="android.widget.SearchView"
    

    from your menu item.

    Add below code to show your menu item:

    app:showAsAction="always"
    

    and in click listener of the optionmenu Use PlaceAutocomplete.IntentBuilder

    int PLACE_AUTOCOMPLETE_REQUEST_CODE = 1;
    ...
    try {
        Intent intent =
                new PlaceAutocomplete.IntentBuilder(PlaceAutocomplete.MODE_FULLSCREEN)
                        .build(this);
        startActivityForResult(intent, PLACE_AUTOCOMPLETE_REQUEST_CODE);
    } catch (GooglePlayServicesRepairableException e) {
        // TODO: Handle the error.
    } catch (GooglePlayServicesNotAvailableException e) {
        // TODO: Handle the error.
    }