Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove/Hide searchView on only one activity

Tags:

java

android

I have 3 activities in my project and I would like to remove/hide the searchView in the actionbar on only one activity.

I tried searchView.setVisibility(View.GONE); but there is still the clickable icon.

main_menu.xml

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

<item android:id="@+id/menu_search"
      android:title="@string/menu_search"
      android:icon="@drawable/ic_menu_search"
      android:showAsAction="ifRoom|collapseActionView"
      android:actionViewClass="android.widget.SearchView" />
<item
    android:id="@+id/item_clear_memory_cache"
    android:title="@string/menu_item_clear_memory_cache"/>

<item
    android:id="@+id/item_clear_disc_cache"
    android:title="@string/menu_item_clear_disc_cache"/>

</menu>
like image 434
GermainGum Avatar asked Jan 14 '13 18:01

GermainGum


3 Answers

menu.findItem(R.id.menu_search).setVisible(false); should be the way.

like image 66
Matthias Robbers Avatar answered Oct 07 '22 08:10

Matthias Robbers


You can hide the searchview and the searchicon by doing this:

searchItem.setVisible(false);
searchView.setVisibility(View.GONE);

Then you can bring it back by:

searchItem.setVisible(true);
searchView.setVisibility(View.VISIBLE);
like image 20
Vikas Avatar answered Oct 07 '22 10:10

Vikas


Well, after some researches here you can find my complete example. Don't forget to set visibility and visible back in activity or fragment where you need to show your search view back.

I was looking a way to hide search view in preferences.

public class SettingsFragment extends PreferenceFragmentCompat {
    @Override
    public void onCreatePreferences(Bundle savedInstanceState, String rootKey) {
        setPreferencesFromResource(R.xml.preferences, rootKey);
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // this means that we're telling the Activity that is hosting the Fragment that we want to display menus
        setHasOptionsMenu(true);
    }

    /**
     * ********************* SEARCH ********************
     */
    @Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        super.onCreateOptionsMenu(menu, inflater);
        final MenuItem item = menu.findItem(R.id.action_search);
        final SearchView searchView = (SearchView) item.getActionView();
        item.setVisible(false);
        searchView.setVisibility(View.GONE);
    }

}

And menu_main.xml

<item android:id="@+id/action_search"
    android:title="@string/action_search"
    app:actionViewClass="androidx.appcompat.widget.SearchView"
    android:icon="@android:drawable/ic_menu_search"
    app:showAsAction="always|collapseActionView"
    />

like image 21
Zhar Avatar answered Oct 07 '22 09:10

Zhar