/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
public PlaceholderFragment() {
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_detail,
container, false);
// The detail Activity called via intent. Inspect the intent for forecast data.
Intent intent=getActivity().getIntent();
TextView text=(TextView)rootView.findViewById(R.id.text1);
String b=intent.getStringExtra(Intent.EXTRA_TEXT);
text.setText(b);
return rootView;
}
}
在这段代码中,当我使用时
TextView text=(TextView)getActivity().findViewById(R.id.text1)
然后我的应用程序崩溃了,Logcat 说
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.View android.view.Window.findViewById(int)' on a null object reference
这是与此代码关联的 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="com.example.sunshine.app.DetailActivity$PlaceholderFragment" >
<TextView
android:id="@+id/text1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/hello_world" />
</RelativeLayout>
在此代码中,当我使用 TextView text=(TextView)getActivity().findViewById(R.id.text1) 时
然后我的应用程序崩溃了,Logcat 说 Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.View android.view.Window.findViewById(int)' on a null object reference
findViewById()
on an Activity
从根视图(称为“装饰视图”)开始,遍历可用小部件和容器的树,寻找 ID 匹配。因此,findViewById()
呼吁Activity
只会查找属于整个活动视图层次结构一部分的视图。
然而,你的inflate()
调用不附加充气RelativeLayout
到活动视图层次结构。这是预料之中的。当附加片段本身时,这些视图将附加到活动视图层次结构,有时在您从onCreateView()
。结果,当你打电话时findViewById()
关于活动从内部onCreateView()
,它找不到你的TextView
, 因为那个TextView
仅由片段管理,尚未成为活动视图层次结构的一部分。
findViewById()
on a View
or ViewGroup
从那开始View
or ViewGroup
并遍历可用小部件和容器的树,寻找 ID 匹配。这RelativeLayout
可以访问您的TextView
,所以当你打电话时findViewById()
on the RelativeLayout
你充气,它起作用了。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)