gpt4 book ai didi

android - 为不同的方向使用不同的布局时,在方向更改时保存 fragment 状态

转载 作者:太空狗 更新时间:2023-10-29 15:01:27 26 4
gpt4 key购买 nike

我对纵向和横向模式有不同的布局。 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>

我的 fragment 是相同的,fragment1.xmlfragment2.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>

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

由于纵向和横向模式的 fragment 不是一个实例,所以我不能使用setRetaintInstanceonSaveInstanceState。我如何在不定义两个 Activity 且不使用 onConfigurationChanged 的情况下做到这一点?

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

最佳答案

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

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", "");

然后根据userInput设置你的editText。

关于android - 为不同的方向使用不同的布局时,在方向更改时保存 fragment 状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26170613/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com