我对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
)
感谢您的帮助。
答案 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;
}