如何解决为什么findViewById在这里不能作为getActivityfindViewById使用?
在这段代码中,当我使用TextView text =(TextView)getActivity()。findViewById(R.id.text1)
然后我的应用程序崩溃了,Logcat说这是由以下原因引起的:java.lang.NullPointerException:尝试在空对象引用上调用虚拟方法’android.view.View android.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() {
}
@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>
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。