java - 来自除主布局之外的其他布局的小部件上的空指针异常

标签 java android xml android-fragments

我正在尝试将各种 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/

相关文章:

java - 如何在没有ImageView的TextView中间添加图像到TextView

php - XML Youtube,是否可以访问yt:accessControl?人物 :

php - 使用 PHP 调用 URL 并获取 XML 响应

java - 使用 Amazon s3 Java SDK 的异常

java - Kit Kat 与所有更高版本(5.x、6.x 和 7.x)之间的 Android 内容提供程序冲突

android - 为什么 setImageBitmap 对自定义 ImageButton 没有影响?

sql-server - `nodes()` 方法是否保持文档顺序?

java - AWS 超时时来自 HTable 的 MapReduce 输入

java - FUSE hibernate 应用程序抛出 No Session found for current thread 异常

java - 单选按钮被选中java