Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Two SearchViews in one Activity and screen rotation

Tags:

java

android

I have two SearchViews in one xml layout:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent">

    <SearchView
        android:id="@+id/my_first_custom_view"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" >
    </SearchView>

   <SearchView
        android:id="@+id/my_second_custom_view"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@id/my_first_custom_view" >
   </SearchView>

</RelativeLayout>

And I inflate this layout to my MainActivity by setContentView(). Then I call methods setQuery() for each other.

Everything is ok until a screen rotation. When I rotate the screen every searchView has text "World" instead "Hello" and "World".

 public class MainActivity extends Activity {

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

        SearchView firstSearchView = (SearchView)     findViewById(R.id.my_first_custom_view);
        SearchView secondSearchView = (SearchView) findViewById(R.id.my_second_custom_view);

        firstSearchView.setQuery("Hello!", false);
        secondSearchView.setQuery("World", false);
    }
}

Someone can explain what's going wrong ?

like image 362
lukjar Avatar asked Feb 22 '13 13:02

lukjar


1 Answers

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.

like image 188
user Avatar answered Nov 11 '22 09:11

user