访问嵌套布局中的Android视图

4

我在从另一个布局中包含的布局中访问Views时遇到了问题。请看这张图片:

http://dl.dropbox.com/u/3473245/layout_includes.png

我该如何通过编程方式访问这4个文本视图? 可能是我忽略了一些非常简单的东西。 非常感谢!

你可以展示一下XML吗?通常你会使用findViewById,这也可以在子视图上完成。 - tidbeck
我认为在你的情况下可以使用getChild()。 - Yury
@tidbeck,我已经将XML粘贴在这里:http://pastebin.com/GyAWsBMy。 - fusion44
@Yury 我已经尝试过了,但是 ViewGroup 似乎一直返回 null。 - fusion44
@fusion44,你尝试过怎样访问它吗?是这样的:View layout = findViewById(R.id.activityBaseLangView); TextView tv = (TextView)layout.findViewById(R.id.languageHeader); - tidbeck
2个回答

10
你可以按照以下步骤进行:

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");

这个 Android 维基页面展示了如何使用可重用的 UI 组件和 XML 布局,但没有展示如何从代码中访问嵌套的可重用组件。
虽然这很简单,但对于那些刚接触 Android 视图的人来说可能不那么清晰。

谢谢!我想这就是我需要的东西。抱歉晚回复了。 - fusion44
这段代码给我抛出了一个NullPointerException(空指针异常)...调试后,我发现问题出在引用包含文件时(第一个“findViewById”)。你知道怎么解决吗? - BurninatorDor

2
以下两行代码可以帮助您获取两个包含文件的 languageHeader,您可以对 languageText 执行相同操作。
``` findViewByid(R.id.activityBaseLangView).findViewById(R.id.languageHeader) findViewByid(R.id.activityLearnLangView).findViewById(R.id.languageHeader) ```

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接