国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 系統 > Android > 正文

AndroidGUI27中findViewById返回null的快速解決辦法

2019-12-12 06:11:20
字體:
來源:轉載
供稿:網友

 在用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的快速解決辦法,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復大家的。在此也非常感謝大家對武林網網站的支持!

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 乌拉特前旗| 三台县| 蕲春县| 汶上县| 资溪县| 哈尔滨市| 班戈县| 保康县| 交口县| 海盐县| 安乡县| 岚皋县| 罗江县| 长兴县| 宿州市| 侯马市| 石嘴山市| 金秀| 左贡县| 保定市| 松潘县| 石泉县| 怀来县| 漳州市| 临洮县| 海兴县| 内黄县| 定安县| 临高县| 获嘉县| 磐安县| 文昌市| 通城县| 滁州市| 墨脱县| 建瓯市| 卢氏县| 枣强县| 九台市| 高密市| 武城县|