发布于 2016-06-25 03:43:17 | 208 次阅读 | 评论: 1 | 来源: 网友投递

这里有新鲜出炉的精品教程,程序狗速度看过来!

Android移动端操作系统

Android是一种基于Linux的自由及开放源代码的操作系统,主要使用于移动设备,如智能手机和平板电脑,由Google公司和开放手机联盟领导及开发。尚未有统一中文名称,中国大陆地区较多人使用“安卓”或“安致”。


这篇文章主要介绍了AndroidGUI27中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对应的代码中,是这样的写的:


@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的快速解决办法,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对phperz网站的支持!



最新网友评论  共有(1)条评论 发布评论 返回顶部
ve 发布于2016-09-06 16:25:07
转来的能不能尊重一下作者!!
支持(0)  反对(0)  回复

Copyright © 2007-2017 PHPERZ.COM All Rights Reserved   冀ICP备14009818号  版权声明  广告服务