问题

这是针对StackOverflow上经常发布的问题的规范问题。
我正在学习一个教程。我使用向导创建了一个新活动。当我尝试使用我的activityonCreate()中的findViewById()获取的355181603s上的方法时,我得到NullPointerException

ActivityonCreate()

@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>

#1 热门回答(68 赞)

该教程可能已过时,尝试创建基于活动的UI,而不是向导生成的代码首选的基于片段的UI。

视图位于片段布局(fragment_main.xml)中,而不是活动布局(activity_main.xml).onCreate()在生命周期中过早,无法在活动视图层次结构中找到它,并返回anull。调用方法onnull会使NPE失效。

首选的解决方案是将代码移动到fragmentonCreateView(),在膨胀的片段layoutrootView上调用findViewById()

@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;
}

作为旁注,片段布局最终将成为活动视图层次结构的一部分,并且只有在运行片段事务之后才能通过activityfindViewById()发现。待处理的片段事务在super.onStart()afteronCreate()中执行。


#2 热门回答(10 赞)

TryOnStart()方法,只需使用

View view = getView().findViewById(R.id.something);

或使用getView().findViewById方法在onStart()中声明任何视图

通过530453602在视图上声明单击侦听器


#3 热门回答(3 赞)

尝试将访问视图转移到片段的onViewCreated方法,因为有时当你尝试访问onCreate方法中的视图时,它们不会在此时呈现,从而导致空指针异常。

@Override
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);
     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();
    }
 }

原文链接