我正在尝试将各种 fragment 添加到操作栏 Activity 中。
这是 fragment 之一(嵌套在主 Activity 内):
public static class ScheduleFragment extends Fragment {
private static final String ARG_SECTION_NUMBER = "section_number";
public static ScheduleFragment newInstance(int sectionNumber) {
ScheduleFragment fragment = new ScheduleFragment();
Bundle args = new Bundle();
args.putInt(ARG_SECTION_NUMBER, sectionNumber);
fragment.setArguments(args);
return fragment;
}
public ScheduleFragment(){
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
View rootView = inflater.inflate(R.layout.schedule_layout, container, false);
return rootView;
}
}
以及各自的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">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text=""
android:id="@+id/textView"/>
</RelativeLayout>
当我打电话时
titles.add((TextView) findViewById(R.id.textView));
titles.get(0).setText(R.string.Departure_Location);
从 MainActivity 类中,我得到空指针异常,我猜测这是因为 R.id.textView 是在“schedule_layout.xml”中定义的,而不是在“main_activity.xml”中定义的。
Android studio 检查器找到了 R.id.textView,即使我在“main_activity.xml”中没有 textView。
那么我到底该如何解决这个问题呢?
最佳答案
这个问题的答案非常简单:
自从我这样做
View rootView = inflater.inflate(R.layout.schedule_layout, container, false);
我将“schedule_layout”添加到rootView,所以基本上,当我这样做时
titles.add((TextView) findViewById(R.id.textView));
我告诉程序从 main_activity 布局中获取 textView,因为没有,所以它返回 null。
所以我需要告诉它从schedule_layout中获取它,方法是:
titles.add((TextView) rootView.findViewById(R.id.textView));
关于java - 来自除主布局之外的其他布局的小部件上的空指针异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31732321/