我無法從另一個佈局中包含的佈局訪問視圖。 請看看這張照片:在嵌套佈局上訪問Android視圖
http://dl.dropbox.com/u/3473245/layout_includes.png
如何編程訪問4組文本的意見? 它可能是我很想念的一件很簡單的事情。 非常感謝!
我無法從另一個佈局中包含的佈局訪問視圖。 請看看這張照片:在嵌套佈局上訪問Android視圖
http://dl.dropbox.com/u/3473245/layout_includes.png
如何編程訪問4組文本的意見? 它可能是我很想念的一件很簡單的事情。 非常感謝!
你可以做如下:
main.xml中
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<include android:id="@+id/item_base_lang" layout="@layout/dictionary_list_item" />
<include android:id="@+id/item_learn_lang" layout="@layout/dictionary_list_item" />
</LinearLayout>
個dictionary_list_item.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="wrap_content" >
<TextView
android:id="@+id/dictionary_list_item_text_header"
android:layout_width="fill_parent"
android:layout_height="wrap_content" />
<TextView
android:id="@+id/dictionary_list_item_text_content"
android:layout_width="fill_parent"
android:layout_height="wrap_content" />
</LinearLayout>
以編程方式設置文本:
((TextView)findViewById(R.id.item_base_lang).findViewById(R.id.dictionary_list_item_text_header)).setText("item_base_lang_header");
((TextView)findViewById(R.id.item_base_lang).findViewById(R.id.dictionary_list_item_text_content)).setText("item_base_lang_content");
((TextView)findViewById(R.id.item_learn_lang).findViewById(R.id.dictionary_list_item_text_header)).setText("item_learn_lang_header");
((TextView)findViewById(R.id.item_learn_lang).findViewById(R.id.dictionary_list_item_text_content)).setText("item_learn_lang_content");
This Android wiki page展示瞭如何使用帶有XML佈局可重用的UI組件,但它並沒有說明如何訪問嵌套的可重用組件來自代碼。
儘管它非常簡單,但對於那些Android視圖相當新穎的人來說可能並不那麼清楚。
謝謝!我認爲這是我需要的。對不起,最近的答案全部 – fusion44 2012-01-30 18:36:03
這段代碼給了我一個NullPointerException ...調試後,我意識到問題是當被包含的文件被引用(在第一個「findViewById」)。你知道如何修復它嗎? – BurninatorDor 2013-02-16 13:04:41
以下兩行應該可以幫助您獲得這兩個包含的languageHeader。您可以爲languageText
做同樣的findViewByid(R.id.activityBaseLangView).findViewById(R.id.languageHeader) findViewByid(R.id.activityLearnLangView).findViewById(R.id.languageHeader)
你可以展示XML嗎?通常你會使用'findViewById',這也可以在子視圖上完成。 – tidbeck 2011-12-28 17:41:10
我認爲你可以在你的案例中使用getChild()。 – Yury 2011-12-28 17:59:57
@tidbeck,我在這裏粘貼了這個xml:http://pastebin.com/GyAWsBMy – fusion44 2011-12-28 19:39:19