繁体   English   中英

在嵌套布局上访问Android视图

[英]Accessing Android views on nested layouts

我无法从另一个布局中包含的布局访问视图。 请看一下这张照片:

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

此Android维基页面显示了如何将可重用的UI组件与XML布局一起使用,但它没有显示如何从代码中访问嵌套的可重用组件。

虽然它相当简单,但对于那些对Android视图不熟悉的人来说可能并不那么清楚。

以下两行应该可以帮助您获得两个包含的languageHeader。 您可以对languageText执行相同的操作

findViewByid(R.id.activityBaseLangView).findViewById(R.id.languageHeader)findViewByid(R.id.activityLearnLangView).findViewById(R.id.languageHeader)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM