这是 StackOverflow 上经常发布的问题的规范问题。
我正在学习教程。我使用向导创建了一个新 Activity 。在我的 Activity onCreate()
中尝试调用使用 findViewById()
获得的 View
上的方法时,我得到 NullPointerException
>.
Activity 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>
最佳答案
本教程可能已经过时,试图创建基于 Activity 的 UI,而不是向导生成的代码首选的基于 fragment 的 UI。
View 在 fragment 布局(fragment_main.xml
)中,而不是在 Activity 布局(activity_main.xml
)中。 onCreate()
在生命周期中太早,无法在 Activity View 层次结构中找到它,并返回 null
。在 null
上调用方法会导致 NPE。
首选的解决方案是将代码移动到 fragment onCreateView()
,在膨胀的 fragment 布局rootView
上调用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;
}
附带说明, fragment 布局最终将成为 Activity View 层次结构的一部分,并且可以通过 Activity findViewById()
发现,但只有在 fragment 事务运行后才能发现。待处理的 fragment 事务在 onCreate()
之后在 super.onStart()
中执行。
关于java - NullPointerException 在 onCreate() 中访问 View ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23653778/