Android 在页边距的主题中获取维度时出错 背景

Android 在页边距的主题中获取维度时出错 背景,android,android-theme,margins,dimension,Android,Android Theme,Margins,Dimension,我正在尝试根据所选主题在listView项目上设置自定义边距值 该应用程序有多个主题,用户可以选择使用哪个主题,我通过调用“setTheme()”来设置 问题 无论我尝试什么,都会出现以下错误: java.lang.UnsupportedOperationException: Can't convert to dimension: type=0x2 请注意,这种情况仅发生在margin属性中,到目前为止,没有其他属性导致这种情况 我试过的 首先,这里是我使用的xml片段 attrs.xml &

我正在尝试根据所选主题在listView项目上设置自定义边距值

该应用程序有多个主题,用户可以选择使用哪个主题,我通过调用“setTheme()”来设置

问题 无论我尝试什么,都会出现以下错误:

java.lang.UnsupportedOperationException: Can't convert to dimension: type=0x2
请注意,这种情况仅发生在margin属性中,到目前为止,没有其他属性导致这种情况

我试过的 首先,这里是我使用的xml片段

attrs.xml

<attr name="listview_item__horizontal_spacing" format="dimension" />
但是由于某种原因,我得到了0作为这个调用的结果。只有在使用它时才有效

问题 发生了什么事?我怎样才能避免这种情况

除了使用代码(膨胀xml时),真的没有办法克服这一点吗

您不需要使用attr-XML,这是您的问题

将所需的值放入res文件夹中名为dimens.xml的文件中(与strings.xml的位置相同)

此文件的外观如下所示:

<resources>
    <dimen name="value1">15dp</dimen>
    <dimen name="value2">20dp</dimen>
</resources>
<RelativeLayout ...
    android:layout_marginLeft="@dimen/value1" >

15dp
20dp
然后在布局XML中,可以直接引用dimen(就像引用字符串一样),如下所示:

<resources>
    <dimen name="value1">15dp</dimen>
    <dimen name="value2">20dp</dimen>
</resources>
<RelativeLayout ...
    android:layout_marginLeft="@dimen/value1" >

或者在定义样式时,在XML中,它看起来像:

 <style name="MyStyle1">
        <item name="android:layout_marginLeft">@dimen/value1</item>
    </style>

@尺寸/价值1
然后是你的另一种风格:

<style name="MyStyle2">
            <item name="android:layout_marginLeft">@dimen/value2</item>
        </style>

@尺寸/价值2

我想根据当前主题设置维度(用户可以选择,然后在真正创建活动之前使用“setTheme()”。您在这里提供的内容完全是静态的。您只需创建逻辑即可进行这些更改。您可以为每种样式设置不同的维度值(即,每种样式都有一个完全不同的值,在dimen文件夹中有自己独特的值)。添加了答案解决方案。您编写的内容仍然非常静态。我需要支持:setTheme(R.style.MyTheme1)和setTheme(R.style.MyTheme2),每个都将边距的维度设置为不同的值。当您在MyTheme1和MyTheme2之间切换时,维度将从Value1更改为Value2-这正是我的答案所显示的,并且是正确的方法。
<style name="MyStyle2">
            <item name="android:layout_marginLeft">@dimen/value2</item>
        </style>