简体   繁体   English

碎片和屏幕方向变化

[英]fragments and screen orientation changes

i do not understand how fragments and screen orientation is supposed to work in android. 我不明白片段和屏幕方向应该如何在android中工作。

I have a fragment defined in XML. 我有一个用XML定义的片段。

The fragment is expensive to create, so i want to re-use it. 该片段创建起来很昂贵,所以我想重用它。

I have code that looks like this: 我有看起来像这样的代码:

@Override
protected void onSaveInstanceState (Bundle outState) {
    super.onSaveInstanceState(outState);
    getSupportFragmentManager().putFragment(outState, "myfrag", mFrag);
}

and

@Override
protected void onRestoreInstanceState (Bundle savedInstanceState) {
    super.onRestoreInstanceState(savedInstanceState);
    mFrag = getSupportFragmentManager().getFragment(savedInstanceState, "myfrag");
}

What I don't understand is how to replace the fragment in XML with the fragment I've re-obtained. 我不明白的是如何用我重新获得的片段替换 XML中的片段。 When i do a screen orientation change, it winds up destroying my activity and re-creating it, but if I can save my fragment and reuse it, it should make orientation changes a lot faster. 当我进行屏幕方向更改时,它会破坏我的活动并重新创建它,但是如果我可以保存片段并重新使用它,它将使方向更改快得多。

tia. tia。

You could create a framelayout in xml and a fragment in code. 您可以在xml中创建框架布局,并在代码中创建片段。 Then add the created fragment to your framelayout. 然后将创建的片段添加到框架布局。 On orientation change you try to find your created fragment by use of a tag or id and do some remove / add actions. 更改方向时,您尝试使用标签或ID查找创建的片段,然后执行一些删除/添加操作。

fragmentmanager.findFragmentByTag(" ... ");
fragmentmanager.add(R.id.fragmentContainer, myFragment, "...");

Something like that. 这样的事情。

http://developer.android.com/guide/topics/fundamentals/fragments.html Take a look at the sub-section "Or, programmatically add the fragment to an existing ViewGroup". http://developer.android.com/guide/topics/fundamentals/fragments.html查看小节“或者,以编程方式将片段添加到现有ViewGroup”。 This is a sub-section of the section "Adding a fragment to an activity". 这是“向活动添加片段”部分的小节。

Kind regards, Bram 亲切的问候,布拉姆

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM