Reference the id of a view inside an “include” layout in xml

前端 未结 2 883
一向
一向 2021-01-13 02:06

I have a button, A, inside special_button.xml, that I reuse on all my activities. Each activity has a root RelativeLayout.

The

相关标签:
2条回答
  • 2021-01-13 02:25

    You can add an id attribute to your <include> like this:

    <include android:id="@+id/someId"
             layout="@layout/special_button"/>
    
    0 讨论(0)
  • 2021-01-13 02:30

    When you use the include tag, you should also specify a new id within that XML, which you can then reference as the id within the RelativeLayout. See the documentation and this sample code:

    You can also override all the layout parameters (any android:layout_* attributes) of the included layout's root view by specifying them in the tag. For example:

    <include android:id="@+id/news_title"
         android:layout_width="match_parent"
         android:layout_height="match_parent"
         layout="@layout/title"/>
    

    EDIT: As @eskimoapps.com points out, there appears to be a known issue doing this with RelativeLayouts, as documented here, but when I run the following code, it is working as OP requests:

    <?xml version="1.0" encoding="utf-8"?>
    <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="match_parent"
        android:layout_height="match_parent" >
    
        <include layout="@layout/special_button"
            android:id="@+id/btn_a_ref"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentBottom="true"
            android:layout_alignParentRight="true"
             />
    
        <Button
            android:id="@+id/B"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentRight="true"
            android:layout_above="@+id/A"     <!-- this still works, despite having warning in Eclipse -->
            android:layout_marginBottom="15dp"
            android:layout_marginRight="20dp" />
    
    </RelativeLayout>
    

    Here is the picture from HierarchyViewer showing the correct layout: id/A below id/B

    enter image description here

    My only thought is that Eclipse doesn't like it since it's statically trying to find the Button within the same layout file. Since <include> and <merge> work dynamically with the LayoutManager, that's probably while this still works as expected.

    Please try and see if this works for you as well.

    0 讨论(0)
提交回复
热议问题