我在一个 xml 布局中有两个 SearchView:
<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>
我通过 setContentView() 将该布局膨胀到我的 MainActivity。然后我调用方法
setQuery() 为彼此。
一切正常,直到屏幕旋转。当我旋转屏幕时,每个 searchView 都有文本“World”,而不是“Hello”和“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);
}
}
有人可以解释出了什么问题吗?
The SearchView
使用膨胀布局文件产生的视图作为其内容。结果,所有的SearchViews
用于活动布局(如您的案例)的内容将具有相同 ID 的视图。当 Android 尝试保存状态来处理配置更改时,它会看到EditTexts
来自SearchViews
具有相同的 id,它将为所有这些恢复相同的状态。
处理这个问题最简单的方法是使用Activity
's onSaveInstanceState
and 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);
}
也看看这个相关问题.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)