一个片段,我有以下2布局文件:findFragmentById返回不存在
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<fragment android:id="@+id/list_fragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1"
class="MyListFragment"/>
</LinearLayout>
(w900dp)
<fragment android:id="@+id/list_fragment"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight=".3"
class="MyListFragment"/>
<fragment android:id="@+id/content_fragment"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight=".7"
class="MyContentFragment"/>
然后在我的活动我有:
public class ReportActivity extends ActionBarActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.report);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
// Get the content fragment
MyContentFragment contentFragment = (MyContentFragment) getSupportFragmentManager().findFragmentById(R.id.content_fragment);
if (contentFragment != null) {
// sometimes I get a handle to this fragment when I should not
contentFragment.updateContent(//some content);
}
}
我的问题是这样的。当我以横向模式启动应用程序时,宽度足以显示这两个片段。当我旋转到纵向时,它不再足够宽,没有内容片段的布局文件被加载。但是,当我调用片段管理器来获取该片段时,它会找到它。然后当我调用更新内容失败,因为该片段内的UI组件不再存在。
为什么getFragmentById返回确实存在的片段,但在设备旋转后不再存在?
谢谢。但是,我不编程创建片段,Android为我做它,因为它们在我的布局文件中。 I.E.我没有发布更多活动代码的原因是因为没有更多。当您在xml布局文件中使用片段标签时,android会创建/销毁片段。 – lostintranslation 2015-04-02 21:57:51
你可能想尝试手动处理它,因为框架似乎没有做得很好。 – athingunique 2015-04-02 21:59:22