【问题标题】:How to reuse layout in android but at the same time use multiple ID?如何在android中重用布局但同时使用多个ID?
【发布时间】:2014-11-14 07:39:38
【问题描述】:

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"/>

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

【问题讨论】:

    标签: android android-layout styles android-xml android-styles


    【解决方案1】:

    试试:

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

    P.S:我还没有测试过,但逻辑上听起来不错。所以让我知道它是否有效。

    【讨论】:

    • 这不起作用,因为 yourLayout1 和 yourLayout2 为空。布局标签 id 不起作用。
    • @Nicola 你在用merge 吗?
    【解决方案2】:
    /**
     * 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);
    }
    

    View 对象也有 findViewById 功能。而且它只找到孩子。所以你可以先找到 bar_1 或 bar_2 ,然后使用 bar_1 或 bar_2 对象的 findViewById 函数来获取你想要的子视图。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-09-06
      • 2014-10-24
      • 1970-01-01
      • 2011-06-26
      • 1970-01-01
      • 2020-12-31
      • 1970-01-01
      • 2017-08-28
      相关资源
      最近更新 更多