我是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; }
总结 以上是内存溢出为你收集整理的片段中的访问TextView引发NullPointerException全部内容,希望文章能够帮你解决片段中的访问TextView引发NullPointerException所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)