NullPointerException accessing views in onCreate()(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().
这篇关于NullPointerException 在 onCreate() 中访问视图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:NullPointerException 在 onCreate() 中访问视图
 
				
         
 
            
        基础教程推荐
- Java 实例变量在两个语句中声明和初始化 2022-01-01
- 大摇大摆的枚举 2022-01-01
- Java Swing计时器未清除 2022-01-01
- 如何在 JFrame 中覆盖 windowsClosing 事件 2022-01-01
- 多个组件的复杂布局 2022-01-01
- 如何在 Spring @Value 注解中正确指定默认值? 2022-01-01
- 在 Java 中创建日期的正确方法是什么? 2022-01-01
- 不推荐使用 Api 注释的描述 2022-01-01
- 验证是否调用了所有 getter 方法 2022-01-01
- 从 python 访问 JVM 2022-01-01
 
    	 
    	 
    	 
    	 
    	 
    	 
    	 
    	 
						 
						 
						 
						 
						 
				 
				 
				 
				