fragments and handling orientation changes

拈花ヽ惹草 提交于 2019-12-22 10:04:29

问题


i have an activity with a fragment in it.

I would like to handle the orientation change myself, so i updated the manifest to look like this:

    <activity android:name="com.test.app" android:configChanges="orientation|keyboardHidden"/>

Then i updated the activity to look like this:

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        updateLayout();
    }

and

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        updateLayout();
    }

    private void updateLayout() {
        setContentView(R.layout.my_layout);
    }

I also do this with the fragment:

    fragment.setRetainInstance(true);

The issue I have is that when I do the screen orientation, it fails on the setContentView() saying that there is a duplicate id for my fragment. Not sure how to make it so that doesn't happen -- ideas?

tia.


回答1:


I believe it's because you told it not to throw away your previous layout, so when you rotate it, you still have your old view (which in this case, is the same as the new view, thus the ID conflicts).

Also, I'm not sure, but I think this:

fragment.setRetainInstance(true);

is unnecessary? Because here you tell it NOT to recreate your activity on configuration changes:

android:configChanges="orientation|keyboardHidden"

In my experience, the configChanges setting in XML is enough to prevent recreation.

EDIT :

Mmmm just looking again, how exactly are you using Fragments? If the code posted here is from your FragmentActivity, then I would expect something like this for inflating your Fragment and adding it to the Activity:

class SomeActivity extends FragmentActivity
{
    ...
    @Override
    public void onCreate( Bundle savedInstance )
    {
    ...
        LayoutInflater inflater = getLayoutInflater();
        inflater.inflate( R.layout.some_fragment, root );
    ...
    }
}

With that XML looking something like: some_fragment.xml

<?xml version="1.0" encoding="utf-8"?>
<fragment
  xmlns:android="http://schemas.android.com/apk/res/android"
  android:orientation="vertical"
  android:layout_width="match_parent"
  android:layout_height="match_parent"
  android:name="com.someapp.fragments.SomeFragment">
</fragment>

So I guess I'm not clear on how you are using Fragments. But using them like this, with the XML config setting, successfully disables recreation on rotation for me.



来源:https://stackoverflow.com/questions/8495095/fragments-and-handling-orientation-changes

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!