开发者

How to use a theme defined variable in res/values/dimens.xml?

Howdy. In my themes.xml definition, I have the following:

<style name="mythemename">
     <item name="d_myvar">100dip</item>
</style>

I would like to be able to reference this in res/values/dimens.xml like so:

<dimen name="myvar">?d_myvar</dimen>

Alas, this doesn't work. When I try to use the @dimen/myvar as the height of a LinearLayout, the app crashes with the error "You must supply a layout height attribute."

I have also tried

  <dimen name="myvar" value="?d_myvar" />

But that won't compile.

How can I define @dim开发者_JS百科en/myvar in my xml so that it loads the ?d_myvar variable defined in the theme?

Thanks!


I saw your help request on the Italian Startup Scene.

Unfortunately, according to the syntax of the dimen tag:

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <dimen
        name="dimension_name"
        >dimension</dimen>
</resources>

you simply can't do it. In fact, you can reference theme attributes when the syntax specifies:

 ?[package:][type:]name

Solutions:

  • Gix's answer would be the standard way of defining and reusing dimensions.

  • Maybe you can reorganize your code to reuse d_myvar through inheritance?

  • As a last and desperate resort, I would go for a shell script that automates the process of variable substitution using xml command line tools. I have never personally used them, but see for example xmllint, xmlstarlet or this article.


Put the 100dip part in your dimens.xml like so:

<dimen name="myvar">100dp</dimen>

then in your theme you can reference it as @dimen/myvar if you need, or you can reference it in code using R.dimen.myvar

In other words, you don't set the dimension in theme and then reference it in dimens.xml, but you go the other way around. You set the dimension in dimens.xml and then reference that in your theme/style xml.


In styles.xml

<resources>

    <attr format="dimension" name="exampleDimension"/>

    <style name="AppTheme" parent="Theme.AppCompat.NoActionBar">
        <item name="exampleDimension">100dp</item>
        ...
    </style>
</resources>

Then in your other xml to use the new attribute, you would use it like this

android:padding="?attr/exampleDimension"
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜