AndroidGUI27中findViewById返回null的快速解决办法

AndroidGUI27中findViewById返回null的快速解决办法,第1张

概述 在用Eclipse进行Android的界面开发,通过findViewById试图获取界面元素对象时,该方法有时候返回null,造成这种情况主要有以下两种情形。

 在用Eclipse进行AndroID的界面开发,通过findVIEwByID试图获取界面元素对象时,该方法有时候返回null,造成这种情况主要有以下两种情形。

第一种情形是最普通的。

比如main.xml如下,其中有一个ListVIEw,其ID为lv_contactbook

<?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="fill_parent"><EditText androID:ID="@+ID/et_search"androID:layout_wIDth="fill_parent"androID:layout_height="wrap_content"androID:text=""/><ListVIEw androID:ID="@+ID/lv_contactbook"androID:layout_wIDth="fill_parent"androID:layout_height="wrap_content"/></linearLayout>

如果在Activity对应的代码中,是这样的写的:

@OverrIDepublic voID onCreate(BundlesavedInstanceState){super.onCreate(savedInstanceState);ListVIEwlv = (ListVIEw)findVIEwByID(R.ID.lv_contactbook);setContentVIEw(R.layout.main);//…}

即在setContentVIEw调用之前,调用了findVIEwByID去找main布局中的界面元素lv_contactbook,那么所得到的lv一定是null。正确的做法是将上面代码中加粗的哪一行,挪至setContentVIEw方法调用之后。

第二种情形。

这种情况下通常是调用LayoutInflater.inflate将布局xml规定的内容转化为相应的对象。比如有rowvIEw.xml布局文件如下(比如在自定义Adapter的时候,用作ListVIEw中的一行的内容的布局):

<?xml version="1.0"enCoding="utf-8"?><linearLayoutxmlns:androID="http://schemas.androID.com/apk/res/androID"androID:orIEntation="horizontal"androID:layout_wIDth="fill_parent"androID:layout_height="wrap_content"> <TextVIEw androID:ID="@+ID/tv_contact_ID"androID:layout_wIDth="0px"androID:layout_height="0px"androID:visibility="invisible"androID:gravity="center_vertical"/><TextVIEw androID:ID="@+ID/tv_contactname"androID:layout_wIDth="wrap_content"androID:layout_height="36dip"androID:textSize="16dip"androID:layout_margintop="10dip"androID:textcolor="#FFFFFFFF"/></linearLayout>

假定在自定的Adapter的getVIEw方法中有类似如下的代码:

VIEw rowvIEw = (VIEw)inflater.inflate(R.layout.rowvIEw,parent,false);TextVIEw tv_contact_ID =(TextVIEw)rowvIEw.findVIEwByID(R.ID.tv_contact_ID);TextVIEw tv_contactname =(TextVIEw)rowvIEw.findVIEwByID(R.ID.tv_contactname);

有时候居然也会发现rowvIEw非空,但tv_contact_ID和tv_contactname都是null!仔细看代码,怎么也看不出错误来。到底是什么原因造成的呢?答案是Eclipse造成的,要解决这个问题,需要这个项目clean一次(Project菜单 -> Clean子菜单),这样就OK了。

第二种情况很隐蔽,因为代码的确没有错。如果一时没有想到解决办法会浪费很多时间。

以上所述是小编给大家介绍的AndroIDGUI27中findVIEwByID返回null的快速解决办法,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对编程小技巧网站的支持!

总结

以上是内存溢出为你收集整理的AndroidGUI27中findViewById返回null的快速解决办法全部内容,希望文章能够帮你解决AndroidGUI27中findViewById返回null的快速解决办法所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址:https://www.54852.com/web/1149141.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-05-31
下一篇2022-05-31

发表评论

登录后才能评论

评论列表(0条)

    保存