Search code examples
javaandroidsearchview

Add Search Button to Toolbar and Start New Activity on Click


I want to add a search magnifying class button to my toolbar. So far, I have the below code:

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
    MenuInflater inflater = getMenuInflater();
    inflater.inflate(R.menu.menu_search, menu);
    SearchView search = (SearchView) MenuItemCompat.getActionView(menu.findItem(R.id.search));
    // Associate searchable configuration with the SearchView
    SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);
    search.setSearchableInfo(searchManager.getSearchableInfo(new ComponentName(this, SearchResultsActivity.class)));
    search.setQueryHint(getResources().getString(R.string.search_hint));
    return true;
}

However, this is not the behavior I am seeking.

I would like for the search to immediately open a new activity, with the capability for the user to type into the toolbar and perform a query right off the bat instead of having to click search again.

The reason - I want to use Algolia to populate search results live. I don't want to do this on the initial Activity; I merely want to allow the user to click search, navigate to a new Activity that is linked with Algolia, and then start typing in the second Activity to see live search results.

Any advice is appreciated!


Solution

  • use this code

    main_menu.xml

    <?xml version="1.0" encoding="utf-8"?>
    
    <item
        android:id="@+id/option_search"
        android:icon="@drawable/icon_search"
        android:orderInCategory="100"
        app:showAsAction="always"
        android:title="Search" />
    

    now in your main activity do like this

    MainActivity.java

        public class MainActivity extends AppCompatActivity {
    
        @Override
        protected void onCreate(@Nullable Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
    
    
        }
    
        @Override
        public boolean onCreateOptionsMenu(Menu menu) {
            MenuInflater inflater = getMenuInflater();
            inflater.inflate(R.menu.main_menu, menu);
            return true;
        }
    
    
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle item selection
        switch (item.getItemId()) {
        case R.id.option_search:
            //go to search
            return true;
        default:
            return super.onOptionsItemSelected(item);
        }
    }
    
    }
    

    this is going to work the way you expect it