gpt4 book ai didi

android - 如何使用 fragment 处理方向变化?

转载 作者:太空宇宙 更新时间:2023-11-03 12:48:13 26 4
gpt4 key购买 nike

我现在有 2 个 fragment ,一个 fragment 处理纵向模式,然后另一个 fragment 处理横向模式。但问题是,当从纵向旋转到横向然后再回到纵向时。它不会显示与第一个肖像模式相同的内容。有什么代码可以解决这个问题吗?

此代码位于 fragment 容器内:

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.frag_holder);

FragmentManager fm = getSupportFragmentManager();

final Fragment fragment = Frag.newInstance(); //Portrait layout
final Fragment fragment2 = Frag2.newInstance(); //Landscape layout

int orientation = getResources().getConfiguration().orientation; //check whether is it portrait or landscape


if(orientation == Configuration.ORIENTATION_PORTRAIT){
Fragment fragTAG = fm.findFragmentByTag(TAG_P);
if(fragTAG == null){
Log.i("test","test");
fm.beginTransaction()
.replace(R.id.fragPlaceHolder, fragment, TAG_P)
.commit(); //Portrait
}
else{
fm.beginTransaction().replace(R.id.fragPlaceHolder,fragTAG).commit();
}

}
if(orientation == Configuration.ORIENTATION_LANDSCAPE){
Fragment fragTAG = fm.findFragmentByTag(TAG_L);
if(fragTAG == null){
fm.beginTransaction()
.replace(R.id.fragPlaceHolder, fragment2, TAG_L)
.commit(); //Landscape
}
else{
fm.beginTransaction().replace(R.id.fragPlaceHolder,fragTAG).commit();
}
}

}

最佳答案

第 1 步:在您的 Activity 中添加配置更改

    <activity android:name=".ui.createtasks.CreateTaskActivity"
android:configChanges="orientation|screenSize|keyboardHidden" > </activity>

第 2 步: 将您的编辑文本值添加到 onSaveInstanceState

 @Override
public void onSaveInstanceState(@NonNull Bundle outState) {
super.onSaveInstanceState(outState);
outState.putCharSequence(KEY_TITLE, et_text.getText().toString());
}

第 3 步: 通过 onViewStateRestored

获取您保存的编辑文本值
    @Override
public void onViewStateRestored(@Nullable Bundle savedInstanceState) {
super.onViewStateRestored(savedInstanceState);

String savedTitle = null;
if (savedInstanceState != null) {
savedTitle = savedInstanceState.getString(KEY_TITLE);
et_text.setText(savedTitle);

}

}

关于android - 如何使用 fragment 处理方向变化?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37957983/

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