laa*_*lto 113 java android nullpointerexception android-fragments
这是针对StackOverflow上经常发布的问题的规范问题.
我正在关注一个教程.我使用向导创建了一个新活动.我NullPointerException试图在我的活动中使用Views获取方法时得到.findViewById()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();
}
}
Run Code Online (Sandbox Code Playgroud)
布局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>
Run Code Online (Sandbox Code Playgroud)
laa*_*lto 69
该教程可能已过时,尝试创建基于活动的UI,而不是向导生成的代码首选的基于片段的UI.
视图位于片段布局(fragment_main.xml)中,而不在活动布局(activity_main.xml)中.onCreate()在生命周期中太早,无法在活动视图层次结构中找到它,并null返回a.调用方法null会导致NPE.
首选的解决方案是将代码移动到片段onCreateView(),调用findViewById()膨胀的片段布局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;
}
Run Code Online (Sandbox Code Playgroud)
作为旁注,片段布局最终将成为活动视图层次结构的一部分,并且可以通过活动发现,findViewById()但仅在片段事务运行之后才能发现.待处理的片段事务在super.onStart()之后执行onCreate().
Tar*_*rma 10
尝试OnStart()方法,只需使用
View view = getView().findViewById(R.id.something);
Run Code Online (Sandbox Code Playgroud)
或使用getView().findViewById方法声明任何视图onStart()
在视图上声明单击侦听器 anyView.setOnClickListener(this);
| 归档时间: |
|
| 查看次数: |
20973 次 |
| 最近记录: |