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

时间:2013-03-08 14:04:41

标签: java android xml 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>

从使用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>

解决方案?

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

1 个答案:

答案 0 :(得分:1)

您可以创建

  

样式属性

,我认为这就是你要找的东西。它们基本上是变量属性。 例如。你可以在themes.xml中使用它

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <!-- You can define attributes here -->
    <attr name="button_radius" format="reference" />
</resources>

其中定义了一个名为: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>

这样,通过更改主题,您可以使用半径的不同值。下面是一个未经改变的形状可绘制方式的未完成示例:

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

用户可以简单地应用不同的样式来使用不同的属性。 我不知道这个例子是否完整地回答了你的问题,但你可以通过在主题中声明属性来做很多事情。这些属性是动态引用。有关可能性的更多信息see this article