没有合适的资源?快使用搜索试试~ 我知道了~
AndroidGUI27中findViewById返回null的快速解决办法
2 下载量 187 浏览量
2020-08-27
05:37:56
上传
评论
收藏 50KB PDF 举报
温馨提示
试读
2页
主要介绍了AndroidGUI27中findViewById返回null的快速解决办法的相关资料,非常不错,具有参考借鉴价值,需要的朋友可以参考下
资源推荐
资源详情
资源评论
AndroidGUI27中中findViewById返回返回null的快速解决办法的快速解决办法
主要介绍了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!仔细看代码,怎么也看不出错误来。到底是
资源评论
weixin_38603219
- 粉丝: 5
- 资源: 953
上传资源 快速赚钱
- 我的内容管理 展开
- 我的资源 快来上传第一个资源
- 我的收益 登录查看自己的收益
- 我的积分 登录查看自己的积分
- 我的C币 登录后查看C币余额
- 我的收藏
- 我的下载
- 下载帮助
安全验证
文档复制为VIP权益,开通VIP直接复制
信息提交成功