Fragment中的findViewById()返回null

时间:2015-10-22 12:05:05

标签: java android android-fragments

我试图让我的faq_fragment.xml

中显示TextView
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content">

    <TextView
        android:id="@+id/question_text"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:textAlignment="center"
        android:text="Title 1"/>

    <TextView
        android:id="@+id/answer_text"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:textAlignment="center"
        android:text="Description 1"
        android:textColor="#33000000"
        android:layout_marginTop="5dp"/>

</LinearLayout>

在我的片段课程中

@Nullable
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    ((TextView)container.findViewById(R.id.question_text)).setText(title);
    ((TextView)container.findViewById(R.id.answer_text)).setText(description);

    return inflater.inflate(R.layout.faq_fragment, container, false);
}

应用程序崩溃,我收到错误:

java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference

2 个答案:

答案 0 :(得分:5)

在使用之前,您需要对视图进行充气。

@Nullable
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.faq_fragment, container, false);
    ((TextView)view .findViewById(R.id.question_text)).setText(title);
    ((TextView)view .findViewById(R.id.answer_text)).setText(description);

    return view;
}

答案 1 :(得分:2)

你应该使用膨胀的观点:

将其更改为:

@Nullable
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.faq_fragment, container, false);
    ((TextView)view.findViewById(R.id.question_text)).setText(title);
    ((TextView)view.findViewById(R.id.answer_text)).setText(description);
    return view;
}