gpt4 book ai didi

android - 在 xml 中的 "include"布局中引用 View 的 id

转载 作者:塔克拉玛干 更新时间:2023-11-02 22:46:10 25 4
gpt4 key购买 nike

我在 special_button.xml 中有一个按钮 A,我在所有 Activity 中重复使用它。每个 Activity 都有一个根 RelativeLayout

问题:我的一个 Activity 有一个按钮 B,与 A 位于同一位置。我决定将 B 移动到 A 上方,但我无法从 Activity 的 xml 中引用 A

这是xml

special_button.xml

<?xml version="1.0" encoding="utf-8"?>
<merge xmlns:android="http://schemas.android.com/apk/res/android" >

<Button
android:id="@+id/A"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentRight="true"
android:layout_marginBottom="15dp"
android:layout_marginRight="20dp"/>

</merge>

layout_main.xml

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

<Button
android:id="@+id/B"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_above="<id to reference button A>"
android:layout_marginBottom="15dp"
android:layout_marginRight="20dp" />

</RelativeLayout>

最佳答案

当您使用 include标记,您还应该在该 XML 中指定一个新 ID,然后您可以在 RelativeLayout 中将其引用为 ID .查看documentation和这个示例代码:

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

编辑:正如@eskimoapps.com 指出的那样,使用 RelativeLayout 执行此操作似乎存在一个已知问题。 s,如文件所示here ,但是当我运行以下代码时,它作为 OP 请求工作:

<?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>

这是来自 HierarchyViewer 的图片,显示了正确的布局:id/A下面id/B

enter image description here

我唯一的想法是 Eclipse 不喜欢它,因为它静态地尝试在同一个布局文件中查找 Button。自 <include><merge>使用 LayoutManager 动态工作,这可能仍然按预期工作。

请尝试看看这是否也适用于您。

关于android - 在 xml 中的 "include"布局中引用 View 的 id,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21127884/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com