NullPointerException 在 onCreate() 中访问视图

这是 StackOverflow 上经常发布的问题的规范问题.

我正在学习教程.我使用向导创建了一个新活动.在我的活动 onCreate() 中尝试调用使用 findViewById() 获得的 View 上的方法时,我得到 NullPointerException>.

I'm following a tutorial. I've created a new activity using a wizard. I get NullPointerException when attempting to call a method on Views obtained with findViewById() in my activity onCreate().

活动onCreate():

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    View something = findViewById(R.id.something);
    something.setOnClickListener(new View.OnClickListener() { ... }); // NPE HERE

    if (savedInstanceState == null) {
        getSupportFragmentManager().beginTransaction()
                .add(R.id.container, new PlaceholderFragment()).commit();
    }
}

布局 XML (fragment_main.xml):

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="packagename.MainActivity$PlaceholderFragment" >

    <View
        android:layout_width="100dp"
        android:layout_height="100dp"
        android:id="@+id/something" />

</RelativeLayout>

推荐答案

本教程可能已经过时,试图创建一个基于活动的 UI,而不是向导生成的代码首选的基于片段的 UI.

The tutorial is probably outdated, attempting to create an activity-based UI instead of the fragment-based UI preferred by wizard-generated code.

视图在片段布局(fragment_main.xml)中,而不是在活动布局(activity_main.xml)中.onCreate() 在生命周期中太早,无法在活动视图层次结构中找到它,并返回 null.在 null 上调用方法会导致 NPE.

The view is in the fragment layout (fragment_main.xml) and not in the activity layout (activity_main.xml). onCreate() is too early in the lifecycle to find it in the activity view hierarchy, and a null is returned. Invoking a method on null causes the NPE.

首选的解决方案是将代码移动到片段onCreateView(),在膨胀的片段布局rootView上调用findViewById():

The preferred solution is to move the code to the fragment onCreateView(), calling findViewById() on the inflated fragment layout rootView:

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
    Bundle savedInstanceState) {
  View rootView = inflater.inflate(R.layout.fragment_main, container,
      false);

  View something = rootView.findViewById(R.id.something); // not activity findViewById()
  something.setOnClickListener(new View.OnClickListener() { ... });

  return rootView;
}

附带说明,片段布局最终将成为活动视图层次结构的一部分,并且可以通过活动 findViewById() 发现,但只有在片段事务运行后才能发现.待处理的片段事务在 onCreate() 之后在 super.onStart() 中执行.

As a side note, the fragment layout will eventually be a part of the activity view hierarchy and discoverable with activity findViewById() but only after the fragment transaction has been run. Pending fragment transactions get executed in super.onStart() after onCreate().

相关文章