如何使用片段处理方向变化? [英] How to handle orientation change using fragment?

查看:65
本文介绍了如何使用片段处理方向变化?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我现在有2个片段,一个片段处理纵向模式,然后另一个处理横向模式.但是问题是,当从纵向旋转到横向然后又回到纵向时.它不会显示与第一个人像模式相同的内容.是否有任何代码可以解决此问题?

I now have 2 fragment, one fragment handle portrait mode then another handle landscape mode. But the problem is that when rotate from portrait to landscape then back to portrait. It will not show the same thing that show on the first portrait mode. Is there any code that can solve this problem?

此代码位于片段持有人内部:

This code is inside the fragment holder:

@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:在您的活动中添加配置更改

Step 1: Add Config changes in your activity

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

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

Step 2: Add your edit text values to 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);

    }

}

这篇关于如何使用片段处理方向变化?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆