问题描述
我有一个活动,其中托管了一个片段.
I have an Activity which hosts a Fragment.
活动布局文件:
<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>
活动的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 ,为什么?
I try to find the fragment in onCreate()
of Activity, and then pass some data to it. But when I findFragmentById(...)
, I got NullpointerException, Why?
推荐答案
在将片段添加到活动之前,您无法执行findFragmentById
.制作setContentView
时,Actvitiy
会扩大布局并将其视图添加到当前窗口.在此布局中有Fragment
的情况下,会将它与xml中提供的给定ID或标记添加到FragmentManager
中.只有在这一刻,您才能在那找到它.因此,您要做的就是将findFragmentById
移到setContentView
下方.
You can't perform a findFragmentById
before adding the fragment to your activity. When you make a setContentView
the Actvitiy
inflates the layout and adds its views to the current window. In the case of having a Fragment
in this layout, it is added with the given Id or Tag provided in the xml to the FragmentManager
. Only in this moment you can find it there. So what you have to do is move the findFragmentById
below the setContentView
.
这篇关于findFragmentById时发生NullpointerException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!