无法在具有saveInstanceState的SearchView上设置可见性

时间:2019-02-28 06:35:54

标签: java android android-view

我的活动有一个包含SearchView的菜单,并且我正在以编程方式设置SearchView可见性。我正在使用saveInstanceState来保存例如旋转之间的Visibility值,但是此方面不起作用:在SearchView可见性在旋转之前消失的情况下,SearchView图标在旋转后显示。

如果在从saveInstanceState中获取team_params的值后进行调试和评估,它似乎已正确设置为8。

我的代码中有几行mSearchView.getVisibility(),但是在设置的saveInstanceState的值和向用户显示的旋转的布局之间都没有命中任何行。

布局:

setVisibility(View.VISIBLE)

活动(onSaveInstanceState):

<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto">
    <!-- "Mark Favorite", should appear as action button if possible -->

    <item android:id="@+id/action_search"
        android:title="@string/action_search"
        app:actionViewClass="androidx.appcompat.widget.SearchView"
        app:showAsAction="ifRoom"/>

活动(菜单设置):

public void onSaveInstanceState(Bundle outState){
    super.onSaveInstanceState(outState);
    switch (mSearchView.getVisibility()){
        case View.VISIBLE:
            outState.putInt("SearchViewVisibility",View.VISIBLE);
        case View.GONE:
            outState.putInt("SearchViewVisibility",View.GONE);
    };
}

真的很感谢任何想法!

1 个答案:

答案 0 :(得分:0)

您应该使用setVisible方法来设置菜单项的可见性。

将代码更改为

// Add this property
MenuItem mSearchMenuItem;

public void onSaveInstanceState(Bundle outState) {
    super.onSaveInstanceState(outState);
    outState.putBoolean("isVisible", mSearchMenuItem.isVisible());
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    MenuInflater inflater = getMenuInflater();
    inflater.inflate(R.menu.main, menu);

    //setup SearchView and callbacks
    mSearchMenuItem = menu.findItem(R.id.action_search);
    if (mSavedInstanceState != null) {
        boolean isVisible = mSavedInstanceState.getBoolean("isVisible", true);
        mSearchMenuItem.setVisible(isVisible);
    }

    mSearchView = (SearchView) mSearchMenuItem.getActionView();
    mSearchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
        @Override
        public boolean onQueryTextSubmit(String query) {
            return true;
        }

        @Override
        public boolean onQueryTextChange(String query) {
            // check whether this change is clearing all text from the search
            if (query.isEmpty()) {
                // close the searchView
                mSearchView.post(new Runnable() {
                    @Override
                    public void run() {
                        mSearchView.clearFocus();
                    }
                });
                mSearchView.setIconified(true);
            }
            return true;
        }
    });
    return true;
}