Search code examples
androidtoolbarsearchview

How to hide\show SearchView from Toolbar?


I have ToolBar and I have defined Searchview as an item:

<menu xmlns:android="http://schemas.android.com/apk/res/android"
    <item
        android:id="@+id/action_search"
        android:icon="@android:drawable/ic_menu_search"
        app:showAsAction="never"
        app:actionViewClass="android.support.v7.widget.SearchView"
        android:title="Search"/>
</menu>

Then I have BaseActivity class where I define Toolbar:

protected final void onCreate(Bundle savedInstanceState, int layoutId)
{
    super.onCreate(savedInstanceState);
    setContentView(layoutId);

    Toolbar myToolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(myToolbar);
    getSupportActionBar().setDisplayShowTitleEnabled(false);

    assert myToolbar != null;

}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    MenuInflater inflater = getMenuInflater();
    inflater.inflate(R.menu.menu, menu);

    return true;
}

I have search activity where I show toolbar and I would like to show searchview. The problem is that APP is crashing with null pointer exception that it can't find SearchView action_search

public class SearchActivity extends BaseActivity {

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

        Toolbar toolbar = findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        SearchView searchview = (SearchView) findViewById(R.id.action_search);
        searchview.setVisibility(SearchView.VISIBLE);

    }
}

What is correct way to show\hide SearchView?


Solution

  • (Kotlin)

    Here is a simple way to show/hide searchview:

        private lateinit var menuItem: MenuItem
        private var mSearchView: SearchView? = null
    
        private fun updateSearchUI(visible: Boolean) {
        if (isChecked) {
            menuItem.isVisible = true
        }else{
            menuItem.isVisible = false
        }
        }
    

    On first load of Activity if you want to check some preferences and show/hide:

    override fun onCreateOptionsMenu(menu: Menu?): Boolean {
        menuInflater.inflate(R.menu.menu, menu)
        menuItem = menu!!.findItem(R.id.shortcut_search)
        mSearchView = menuItem.actionView as SearchView
        updateSearchUI(PreferenceManager.getVisibilityStatus(applicationContext))
        return true
    }
    

    if you want to toggle searchView show/hide:

    switch_on_off.setOnCheckedChangeListener { buttonView, isChecked ->
        updateSearchUI(isChecked)
        }
    }