Implementing SearchView as per the material design guidelines

前端 未结 7 850
梦谈多话
梦谈多话 2020-12-04 05:04

I have been looking for ways to implement a searchview in the activity toolbar (actionbar) as per the material design guidelines.

On clicking on the search icon, the

7条回答
  •  不思量自难忘°
    2020-12-04 05:43

    It is actually quite easy to do this, if you are using android.support.v7 library.

    Step - 1

    Declare a menu item

    
    

    Step - 2

    Extend AppCompatActivity and in the onCreateOptionsMenu setup the SearchView.

    import android.support.v7.widget.SearchView;
    
    public class YourActivity extends AppCompatActivity {
    
        ...
    
        @Override
        public boolean onCreateOptionsMenu(Menu menu) {
            getMenuInflater().inflate(R.menu.menu_home, menu);
            // Retrieve the SearchView and plug it into SearchManager
            final SearchView searchView = (SearchView) MenuItemCompat.getActionView(menu.findItem(R.id.action_search));
            SearchManager searchManager = (SearchManager) getSystemService(SEARCH_SERVICE);
            searchView.setSearchableInfo(searchManager.getSearchableInfo(getComponentName()));
            return true;
        }
    
        ... 
    }
    

提交回复
热议问题