当前位置: 移动技术网 > IT编程>移动开发>Android > AndroidGUI27中findViewById返回null的快速解决办法

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

2019年07月24日  | 移动技术网IT编程  | 我要评论

弃妇不乖有种休我,萧方方,酒精比重计

 在用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对应的代码中,是这样的写的:

@override
public 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"?>
<linearlayout
xmlns: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的快速解决办法,希望对大家有所帮助

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网