3

我对纵向和横向模式有不同的布局。layout\activity_main.xml

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

    <FrameLayout android:id="@+id/container"
        android:layout_height="match_parent"
        android:layout_width="match_parent"/>

</RelativeLayout>

并且layout-large\activity_main.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="horizontal" >

    <fragment
        android:id="@+id/fragment1"
        android:name="com.example.fragmentorientationchangetest.Fragment1"
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_weight="1" />

    <fragment
        android:id="@+id/fragment2"
        android:name="com.example.fragmentorientationchangetest.Fragment2"
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_weight="1" />

</LinearLayout>

我的片段是相同的,fragment1.xml并且fragment2.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"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    >

    <TextView
        android:id="@+id/text"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Fragment 2" />

    <EditText android:id="@+id/input"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_margin="4dp"
        android:layout_below="@+id/text"/>
</RelativeLayout>

我想要的是当我在片段的编辑文本中输入一些文本并旋转屏幕时,编辑文本不会丢失其输入文本。

由于纵向和横向模式下的片段不是一个实例,我不能使用setRetaintInstanceor onSaveInstanceState。在不定义两个活动且不使用的情况下如何做到这一点onConfigurationChanged

注意:无需添加任何代码,每个片段都会保存其数据。因此,如果我以纵向模式在 fragment2 中输入一些文本并旋转到横向并再次旋转到纵向模式,我会看到输入的文本。

4

1 回答 1

0

随着我编写更多代码,我有时会忽略简单的想法,例如:

SharedPreferences myText = getSharedPreferences("txt", 0);
SharedPreferences.Editor editor = settings.edit();
editor.putString("userText", "Your text that you want to save");
editor.commit();

和阅读:

SharedPreferences myText = context.getSharedPreferences("txt", 0);
String userInput = myText .getString("userText", "");

然后根据设置您的editText userInput

于 2014-10-03T01:54:06.793 回答