【问题标题】:NullpointerException when findFragmentById当 findFragmentById 出现 NullpointerException
【发布时间】:2015-03-22 11:22:11
【问题描述】:

我有一个 Activity,它承载了一个 Fragment

Activity 布局文件:

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/fragment_container"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <fragment class="com.my.ContentFragment"
        android:id="@+id/fragment_content"
        android:layout_width="match_parent"
        android:layout_height="match_parent"/>
</FrameLayout>

Activity的Java代码:

import android.support.v4.app.Fragment;
import android.support.v7.app.ActionBarActivity;

public class ContentActivity extends ActionBarActivity {

     @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);

            //data from  previous Activity
            Bundle data = getIntent().getExtras();

            Fragment contentFragment = getSupportFragmentManager()
                                                    .findFragmentById(R.id.fragment_content);

            //Pass data to fragment
            /*NullpointerException, contentFragment is null!*/
            contentFragment.setArguments(data);

            setContentView(R.layout.activity_main);
        }
...   
}

我尝试在Activity的onCreate()中找到片段,然后传递一些数据给它。但是当我findFragmentById(...)时,我得到了NullpointerException,为什么?

【问题讨论】:

标签: android android-intent android-fragments android-activity


【解决方案1】:

你应该搬家

 setContentView(R.layout.activity_main);

之前

  Fragment contentFragment = getSupportFragmentManager().findFragmentById(R.id.fragment_content);

您获得了 NPE,因为 findFragmentById(R.id.fragment_content) 未能找到 ID 为 fragment_content片段

【讨论】:

  • @user842225 如果此解决方案不起作用,那么您为什么要接受答案。
【解决方案2】:

在将片段添加到您的活动之前,您不能执行findFragmentById。当您创建setContentView 时,Actvitiy 会膨胀布局并将其视图添加到当前窗口。如果此布局中有Fragment,则将其与xml 中提供的给定ID 或标签一起添加到FragmentManager。只有在这一刻,你才能在那里找到它。所以你要做的就是把findFragmentById移到setContentView下面。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-08-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多