Two SearchViews in one Activity and screen rotation

前端 未结 3 798
耶瑟儿~
耶瑟儿~ 2021-01-05 09:14

I have two SearchViews in one xml layout:



        
相关标签:
3条回答
  • 2021-01-05 09:25

    One way to alleviate this problem is to capture the orientation event change with your activity and then set the query again on your two search views.

    0 讨论(0)
  • 2021-01-05 09:32

    The SearchView uses as its content the view resulted from inflating a layout file. As a result, all the SearchViews used in the layout of an activity(like your case) will have as content, views with the same ids. When Android will try to save the state to handle the configuration change it will see that the EditTexts from the SearchViews have the same id and it will restore the same state for all of them.

    The simplest way to handle this issue is to use the Activity's onSaveInstanceState and onRestoreInstanceState like this:

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        // state for the first SearchView
        outState.putString("sv1", firstSearchView.getQuery().toString());
        // state for the second SearchView
        outState.putString("sv2", secondSearchView.getQuery().toString());
    }
    
    @Override
    protected void onRestoreInstanceState(Bundle savedInstanceState) {
        super.onRestoreInstanceState(savedInstanceState);
        // properly set the state to balance Android's own restore mechanism
        firstSearchView.setQuery(savedInstanceState.getString("sv1"), false);
        secondSearchView.setQuery(savedInstanceState.getString("sv2"), false);
    }
    

    Also have a look at this related question.

    0 讨论(0)
  • 2021-01-05 09:39

    Add this to manifest in activity in which you are having two SearchView

     android:configChanges="keyboardHidden|orientation|screenSize"
    
    0 讨论(0)
提交回复
热议问题