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了。

 

第二種情況很隱蔽,因爲代碼的確沒有錯。如果一時沒有想到解決辦法會浪費很多時間。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章