如何在 Android XML 中继承字段?

3
我希望为第一个ImageView元素设置一些属性,然后在其他元素中继承这些属性。
以下代码无效,但可能存在类似的解决方案?
<ImageView
            android:id="@+id/myimage"
            android:layout_height="100dp"
            android:layout_width="100dp"/>

<ImageView
            android:id="@+id/myimage2"
            android:layout_height="@myimage/layout_height"
            android:layout_width="@myimage/layout_width"/>

你需要在res>values下创建一个dimens.xml资源文件,并将其用于任何你想要的XML元素。 - shadygoneinsane
那么我不能在同一个文件内进行交叉引用吗? - membersound
你可以为它制定样式。 - R.R.M
1
你可以使用一个维度,例如在res/values/dimens.xml中添加<dimen name="myimageheight">100dp</dimen>以及android:layout_height="@dimens/myimageheight"(在需要的地方重复此步骤)。 - MikeT
这样做的目的是什么?如果是为了可重用性,请查看此链接:https://developer.android.com/guide/topics/resources/more-resources.html#Dimension。 - BakaWaii
我想在第一个ImageView上设置一个不可见的第二个ImageView叠加层,并通过编程方式显示它。因此,它必须与底层元素的大小相同。 - membersound
1个回答

2
你不能用那种方式做,但是这里有两个选项:
选项1:将值声明为尺寸然后使用它:
在“res/values”目录下的“dimens.xml”中声明高度和宽度的两个值。
<dimen name="image_width">100dp</dimen>
<dimen name="image_height">100dp</dimen>

然后在您的 XML 中像这样使用它们:

<ImageView
        android:id="@+id/myimage2"
        android:layout_height="@dimen/image_height"
        android:layout_width="@dimen/image_width"/>

选项2: 创建与您的ImageView关联的style:

首先要做的是创建您的视图的样式并将其放置在styles.xml中,该文件可以在res/values中找到。

<style name="my_image_view_style">
    <item name="android:layout_height">100dp</item>
    <item name="android:layout_width">100dp</item>
</style>

将您创建的style添加到ImageView中:
<ImageView
        android:id="@+id/myimage2"
        style="@style/my_image_view_style"/>

<style> looks promising. But trying to use it states "attribute is missing the android namespace". Where do I have to put those styles? In the same file, or in a different one? - membersound
你需要在resources中的styles.xml文件中声明它。我会编辑我的答案,使其更易于理解。 - Iulian Popescu

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接