XML资源中的变量 - 将值从父级传递给子级

Cel*_*Cel 12 java xml android android-layout

我正在尝试重用原始形状,并使用这些声明性XML元素组成我的大部分用户界面.

如何制作变量Android属性?

但我不想为每个属性值及其排列创建单独的XML文件,并且在此过程中复制了大部分工作.

例如,我希望这个形状的消费者能够定义android:radius值?

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
    <gradient
            android:startColor="#449def"
            android:endColor="#2f6699"
            android:angle="270"/>
    <stroke
            android:width="1dp"
            android:color="#2f6699"/>
    <corners
            android:radius="3dp"/>
</shape>
Run Code Online (Sandbox Code Playgroud)

使用XML父级设置属性?

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_pressed="true" android:drawable="@drawable/shape_box_round_blue_uniform" />
    <!-- How to set the corner radius here? -->
    <item android:drawable="@drawable/shape_box_round_blue" />
</selector>
Run Code Online (Sandbox Code Playgroud)

解决方案?

  • 如果可能的话,我不想使用任何Java代码隐藏/避免创建自定义控件/类的需要
  • 使用维度资源可能是一个富有成效的途径?

Ent*_*eco 4

您可以创建

风格属性

,我认为这就是您正在寻找的。它们基本上是可变属性。例如,您可以在您的 theme.xml 中使用它

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <!-- You can define attributes here -->
    <attr name="button_radius" format="reference" />
</resources>
Run Code Online (Sandbox Code Playgroud)

它定义了一个名为:button_radius 的变量引用,它可以在样式或布局 xml 文件中使用:

<!-- You can use them like so: -->
<style name="MyApp.Theme1" parent="android:Theme.Holo.Light">
    <item name="button_radius">12</item>
</style>

<style name="MyApp.Theme2" parent="android:Theme.Holo.Light">
    <item name="button_radius">36</item>
</style>
Run Code Online (Sandbox Code Playgroud)

这样,通过更改主题,您可以使用不同的半径值。下面是一个未经测试的示例,说明如何更改可绘制的形状:

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
    <gradient
        android:startColor="#449def"
        android:endColor="#2f6699"
        android:angle="270"/>
    <stroke
        android:width="1dp"
        android:color="#2f6699"/>
    <corners
        android:radius="?button_radius"/> <!-- NOTE the ?button_radius-->
</shape>
Run Code Online (Sandbox Code Playgroud)

用户只需应用不同的样式即可使用不同的属性。我不知道这个示例是否完整地回答了您的问题,但是通过在主题中声明属性您可以做很多事情。这些属性是动态引用。有关可能性的更多信息,请参阅这篇文章