简体   繁体   中英

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 @dimen/myvar in my xml so that it loads the ?d_myvar variable defined in the theme?

Thanks!

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"

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.

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM