【问题标题】:getActivity() in fragment returns null after orientation change方向改变后片段中的getActivity()返回null
【发布时间】:2015-04-13 18:09:16
【问题描述】:

我已经设置了一个应用程序来使用主/详细模式,即在横向模式下同时显示一个列表视图和有关所选项目的详细信息,并且只有列表视图 + 启动新活动以在纵向模式下进行详细视图。

一切似乎都很完美,直到我将方向更改为横向模式后尝试在我的主片段中使用 getActivity() 时出现 NullPointerException。奇怪的是,它在我改变方向(并变回纵向)之前和之后都以纵向模式工作!

我是在用户按下按钮时调用getActivity(),所以肯定是在activity创建之后,getActivity不应该返回null,对吧?

【问题讨论】:

    标签: android android-fragments


    【解决方案1】:

    问题似乎源于我的 XML 布局。我在纵向模式和横向模式下有不同的布局,如下所示:

    肖像.xml

    <?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="wrap_content"
        android:orientation="horizontal" >
    
    
            <fragment
                android:id="@+id/PageFragment"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:name="com.magnuswikhog.adrlibrary.MasterFragment" />                    
    
    
    </LinearLayout>
    

    风景.xml

    <?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="wrap_content"
        android:orientation="horizontal"
        android:baselineAligned="false" >
    
    
            <fragment
                android:id="@+id/MasterFragment"
                android:layout_weight="1"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:name="com.magnuswikhog.adrlibrary.MasterFragment" />                    
    
            <fragment
                android:id="@+id/DetailsFragment"
                android:layout_weight="1"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:name="com.magnuswikhog.adrlibrary.DetailsFragment" />                   
    
    </LinearLayout>
    

    请注意,MasterFragment 元素在 Portrait.xml 中具有 id="PageFragment",在 Landscape.xml 中具有 id="MasterFragment"。当我在 Portrait.xml 中将其更改为“MasterFragment”时,问题也消失了!因此,请确保所有布局中相同片段的 id 相同。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-05-05
      • 1970-01-01
      • 1970-01-01
      • 2013-12-31
      • 2012-07-22
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多