Java 来自除主布局以外的其他布局的小部件上的空指针异常
我正在尝试将各种片段添加到动作栏活动中 以下是一个片段(嵌套在主活动中): 以及相应的xml:Java 来自除主布局以外的其他布局的小部件上的空指针异常,java,android,xml,android-fragments,Java,Android,Xml,Android Fragments,我正在尝试将各种片段添加到动作栏活动中 以下是一个片段(嵌套在主活动中): 以及相应的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="ma
<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">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text=""
android:id="@+id/textView"/>
</RelativeLayout>
在MainActivity类中,我得到了Null指针异常,我猜这是因为R.id.textView是在“schedule_layout.xml”中定义的,而不是在“main_activity.xml”中定义的
Android studio checker会找到R.id.textView,即使我在“main_activity.xml”中没有textView
那么,我如何才能准确地解决这个问题呢?答案非常简单: 因为我知道
View rootView = inflater.inflate(R.layout.schedule_layout, container, false);
我将“schedule_layout”添加到根视图中,因此基本上,当我这样做时
titles.add((TextView) findViewById(R.id.textView));
我告诉程序从主活动布局中获取textView,因为没有,所以返回null
所以我需要告诉它从schedule_layout中获取它,方法是:
titles.add((TextView) rootView.findViewById(R.id.textView));
答案很简单: 因为我知道
View rootView = inflater.inflate(R.layout.schedule_layout, container, false);
我将“schedule_layout”添加到根视图中,因此基本上,当我这样做时
titles.add((TextView) findViewById(R.id.textView));
我告诉程序从主活动布局中获取textView,因为没有,所以返回null
所以我需要告诉它从schedule_layout中获取它,方法是:
titles.add((TextView) rootView.findViewById(R.id.textView));
还要添加异常跟踪。什么是“标题”以及在哪里声明?另外,请澄清您到底想要实现什么。您需要在MainActivity.javaI中包含NPE发生的代码块,并添加异常跟踪。我澄清了什么是标题,我想要实现的是能够从另一个xml文件中使用textView。当我调用“titles.get(0).setText(R.string.deference_Location);”时会出现NPE,同时添加异常跟踪。“titles”是什么,它在哪里声明?另外,请澄清您到底想要实现什么。您需要在MainActivity.javaI中包含NPE发生的代码块,并添加异常跟踪。我澄清了什么是标题,我想要实现的是能够从另一个xml文件中使用textView。当我调用“titles.get(0).setText(R.string.department_Location);”时会出现NPE