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 ?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With