Java 一个活动和屏幕旋转中的两个搜索视图
我在一个xml布局中有两个搜索视图:Java 一个活动和屏幕旋转中的两个搜索视图,java,android,Java,Android,我在一个xml布局中有两个搜索视图: <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 a
<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>
有人可以解释问题出在哪里?缓解此问题的一种方法是捕获活动中的方向事件更改,然后在两个搜索视图上再次设置查询。将此添加到有两个
搜索视图的活动中的清单中
android:configChanges="keyboardHidden|orientation|screenSize"
SearchView
将膨胀布局文件所产生的视图用作其内容。因此,在活动(如您的案例)布局中使用的所有搜索视图
都将具有相同ID的视图作为内容。当Android试图保存状态以处理配置更改时,它将看到来自searchview
的editText
具有相同的id,并且它将为所有这些视图恢复相同的状态
处理此问题的最简单方法是使用活动的onSaveInstanceState
和onRestoreInstanceState
如下:
@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);
}
还可以看看这个。这是您的SearchView在onCreate中获得的唯一引用吗?我想没有。。如果没有,那么你可能想发布相关的代码我尝试了你的代码,并有与你相同的行为。。。所以所有重现问题的东西都在后面是的,这是唯一的参考。我不再使用它了。你能写一些更有趣的东西吗?这并不太复杂,谷歌如何在你的活动中收听方向的变化,然后重新配置你的两个搜索视图。@请检查我的答案,并通知我这是否有用。嗯……这不是问题的答案。这是一种变通方法,但也有一些缺点。这对我来说不是一个好的解决方案,但我承认它也有效。我在SearchView中查找bug。此外,我的活动应该在屏幕旋转后重新创建,我不想更改其默认行为。谢谢你的回答。我想这可能对某人有帮助。谢谢。它有效;)。在这种情况下,onRestoreInstanceState()方法中的restore实例非常重要。在onCreate中执行此操作时,它不起作用。onCreate中的值“Hello”和“World”可能在onRestore方法中被重写。
@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);
}