我是Android开发的新手.
我在布局中有一个TextView,当我尝试在Fragment类中访问TextView时,抛出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调用相关片段)
谢谢你的帮助.
解决方法:
在您的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;
}