在Fragment中访问TextView会抛出NullPointerException

时间:2013-01-24 06:31:29

标签: android android-fragments textview

我对Android开发很新。

我在布局中有TextView,当我尝试访问TextView类中的Fragment时,会抛出NullPointerException。我正在访问TextView,如下所示......

TextView textView = (TextView) view.findViewById(R.id.quotes);

我做错了什么?

我已经在SO上查看过有关此问题的其他答案,但尚未找到解决方案......

相关代码

quotes_details_fragment.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

    <TextView
        android:id="@+id/quotes"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true"
        android:text="@string/quotes_details"
        android:textSize="24sp" />

</RelativeLayout>

QuotesFragment.java

public class QuotesFragment extends Fragment {

    public QuotesFragment() {
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view =  inflater.inflate(R.layout.quotes_details_fragment, container, false);
        TextView textView = (TextView) view.findViewById(R.id.quotes); // NullPointerException
        return view;
    }

}

(主要活动类仅使用FragmentTransaction

调用相关片段

感谢您的帮助。

1 个答案:

答案 0 :(得分:4)

在onCreateView(..);

中添加此LayoutInflater
 LayoutInflater lf = getActivity().getLayoutInflater();   

像这样:

 @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        // Inflate the layout for this fragment

        LayoutInflater lf = getActivity().getLayoutInflater();   

        View view =  lf.inflate(R.layout.quotes_details_fragment, container, false);
        TextView textView = (TextView) view.findViewById(R.id.quotes); // 
        return view;
    }