Android的碎片问题与方向改变 [英] android Fragment issue with orientation change

查看:152
本文介绍了Android的碎片问题与方向改变的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有活动,两个布局为它定义:

I have activity and two layouts for it defined:


  1. 布局大土地

  2. 布局

1的布局是在横向模式下大屏幕,第二是其他案件。
首届布局包含:

1st layout is for large screens in landscape mode, 2nd is for other cases. The 1st layout contains:


  1. 片段1

  2. fragment2

第二布局包含:


  1. 片段1

当我开始在横向模式下的应用大屏幕上时, getSupportFragmentManager()。findFragmentById() Activity.onCreate()正确返回两个片段。方向改变为纵向后, getSupportFragmentManager()。findFragmentById() fragment2 返回不为空,但它应该返回因为这个片段在此布局中定义。问题是返回的片段对象是不正确的,我得到指针异常而访问它。它应该是,不应该吗?

When I start the app in landscape mode on large screen, the getSupportFragmentManager().findFragmentById() called in Activity.onCreate() correctly returns both fragments. After orientation change to portrait, getSupportFragmentManager().findFragmentById() returns not null for fragment2, but it should return null because this fragment is not defined in this layout. The problem is that the returned fragment object is incorrect and I get null pointer exceptions while accessing it. It should be null, shouldn't it?

推荐答案

其实...我不认为它应该是

Actually... I don't think it should be null.

在你的布局大土地布局显示在活动活动将增加在 FragmentManager 的两个片段。一旦你旋转你的活动 FragmentManager 保留它的状态,而片段里面,它仍然有一个 Fragment2 在里面,这就是为什么 findFragmentById()做不返回

After your layout-large-land layout is displayed in the Activity, the Activity will add those both Fragments in the FragmentManager. Once you rotate your Activity, the FragmentManager retains it's state, and the Fragments inside it, and it still has that Fragment2 in it, and that is why findFragmentById() does not return null.

Fragment2 将在那里,但它不会附着在活动,您可以检查这种通过使用 fragment.isAdded() fragment.isVisible()

The Fragment2 will be there, but it won't be attached to the Activity, and you can check this by using fragment.isAdded() or fragment.isVisible().

如果你的情况,你要知道,如果你的2窗格(横向)或1窗格(纵向),也许你应该做以下检查: findViewById(R.id.secondFragmentContainer) == NULL

If in your case, you want to know if your 2-pane (landscape) or 1-pane(portrait), maybe you should do the following check : findViewById(R.id.secondFragmentContainer)==null.

这篇关于Android的碎片问题与方向改变的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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