为什么findViewById()在这里不能作为getActivity()。findViewById()使用?

【字号: 日期:2024-02-23浏览:40作者:雯心
如何解决为什么findViewById()在这里不能作为getActivity()。findViewById()使用??

在这段代码中,当我使用TextView text =(TextView)getActivity()。findViewById(R.id.text1)

然后我的应用程序崩溃了,Logcat说这是由以下原因引起的:java.lang.NullPointerException:尝试在空对象引用上调用虚拟方法’android.view.Viewandroid.view.Window.findViewById(int)’

findViewById()上的Activity从根视图(所谓的“装饰视图”)和横穿可用的小部件和容器,寻找一个ID匹配的树开始。因此,findViewById()在上调用Activity只会发现属于整体活动视图层次结构的视图。

但是,您的inflate()呼叫不会将膨胀的内容附加RelativeLayout到活动视图层次结构。这是预期的。当片段本身被附加时,这些视图将被附加到活动视图层次结构中onCreateView()。结果,当您从内部 调用findViewById()活动时onCreateView(),它找不到您的TextView,因为该活动TextView仅由片段管理,还不是活动视图层次结构的一部分。

findViewById()上View或ViewGroup从开始View或ViewGroup与横梁可用的widget和容器,找一个ID匹配的树。在RelativeLayout访问你的TextView,所以当你打电话findViewById()的RelativeLayout,你膨胀,它的工作原理。

解决方法

/** * A placeholder fragment containing a simple view. */ public static class PlaceholderFragment extends Fragment {public PlaceholderFragment() {}@Overridepublic 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' > <TextViewandroid: android:layout_width='wrap_content'android:layout_height='wrap_content'android:text='@string/hello_world' /></RelativeLayout>

相关文章: