繁体   English   中英

如何在android中重用布局,但同时使用多个ID?

[英]How to reuse layout in android but at the same time use multiple ID?

http://developer.android.com/training/improving-layouts/reusing-layouts.html

本网站介绍

<include layout="@layout/titlebar"/>

重用布局,所以我可能会这样编码,问题是

<include layout="@layout/titlebar"
 android:id="@+id/bar_1"/>

<include layout="@layout/titlebar"
 android:id="@+id/bar_2"/>

如果标题栏是线性布局,并且我想在titlebar中获取textview ,如何区分栏1和栏2? 谢谢

尝试:

// Get root View id from that include link
View yourLayout1 = findViewById(R.id.bar1); 
View yourLayout2 = findViewById(R.id.bar2); 

// Get text view contained inside the include file
TextView yourTextView1 = (TextView)(yourLayout1.findViewById( R.id.yourInnerTextview )); 
TextView yourTextView2 = (TextView)(yourLayout2.findViewById( R.id.yourInnerTextview ));

PS:我还没有测试过,但是从逻辑上讲还不错。 所以,让我知道它是否有效。

/**
 * Look for a child view with the given id.  If this view has the given
 * id, return this view.
 *
 * @param id The id to search for.
 * @return The view that has the given id in the hierarchy or null
 */
public final View findViewById(int id) {
    if (id < 0) {
        return null;
    }
    return findViewTraversal(id);
}

视图对象还具有findViewById函数。 而且它只能找到孩子。 因此,您可以首先找到bar_1或bar_2,然后使用bar_1对象或bar_2对象的findViewById函数来获取所需的子视图。

暂无
暂无

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

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