一个Activity和屏幕旋转中的两个SearchView

时间:2013-02-22 13:01:36

标签: java android

我在一个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);
    }
}

有人可以解释出现了什么问题吗?

3 个答案:

答案 0 :(得分:12)

SearchView使用通过膨胀布局文件产生的视图作为其内容。因此,活动布局中使用的所有SearchViews(如您的情况)都将具有相同ID的内容视图。当Android尝试保存状态以处理配置更改时,它会看到EditTexts中的SearchViews具有相同的ID,并且它将为所有这些状态恢复相同的状态。

处理此问题的最简单方法是使用Activity的{​​{1}}和onSaveInstanceState,如下所示:

onRestoreInstanceState

另请查看此related question

答案 1 :(得分:-1)

缓解此问题的一种方法是使用您的活动捕获方向事件更改,然后在两个搜索视图上再次设置查询。

答案 2 :(得分:-2)

将此添加到您有两个SearchView

的活动中的清单
 android:configChanges="keyboardHidden|orientation|screenSize"