将浮点值添加到 android 资源/值 [英] Add floating point value to android resources/values

查看:22
本文介绍了将浮点值添加到 android 资源/值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 android:lineSpacingMultiplier 在我的 TextViews 的行之间添加一点空间来自文档:

I'm trying to add a little space between lines to my TextViews using android:lineSpacingMultiplier from the documentation:

文本行之间的额外间距,作为乘数.

Extra spacing between lines of text, as a multiplier.

必须是浮点值,例如作为1.2".

Must be a floating point value, such as "1.2".

当我在几个不同的 TextViews 中使用它时,我想为我的资源添加一个全局维度/值,但我不知道要使用哪个标签,如果它甚至存在的话.我已经尝试了所有对我有意义的 资源类型,但是它们都不起作用.

As I'm using this in a few different TextViews I would like to add a global dimension/value to my resources, but I don't know which tag to use, if it even exists. I have tried all resource types that make sense to me, but none of them works.

我想要的是这样的:

<resources>
    <dimen name="text_line_spacing">1.4</dimen>
</resources>

我知道 android:lineSpacingExtra (它需要一个带有附加单位的维度),但我想尽可能使用 android:lineSpacingMultiplier.

I'm aware of android:lineSpacingExtra (which needs a dimension with an appended unit), but I'd like to use android:lineSpacingMultiplier if possible.

推荐答案

有解决办法:

<resources>
    <item name="text_line_spacing" format="float" type="dimen">1.0</item>
</resources>

这样,您的浮点数将在@dimen 下.请注意,您可以使用其他格式"和/或类型"修饰符,其中格式代表:

In this way, your float number will be under @dimen. Notice that you can use other "format" and/or "type" modifiers, where format stands for:

格式 = 封闭数据类型:

Format = enclosing data type:

  • 浮动
  • 布尔值
  • 分数
  • 整数
  • ...

类型代表:

Type = 资源类型(用 R.XXXXX.name 引用):

Type = resource type (referenced with R.XXXXX.name):

  • 颜色
  • 尺寸
  • 字符串
  • 风格
  • 等等……

要从代码中获取资源,您应该使用以下代码段:

To fetch resource from code, you should use this snippet:

TypedValue outValue = new TypedValue();
getResources().getValue(R.dimen.text_line_spacing, outValue, true);
float value = outValue.getFloat();  

我知道这很令人困惑(您会期望像 getResources().getDimension(R.dimen.text_line_spacing) 这样的调用),但 Android dimensions 有特殊处理纯浮点"数不是有效维度.

I know that this is confusing (you'd expect call like getResources().getDimension(R.dimen.text_line_spacing)), but Android dimensions have special treatment and pure "float" number is not valid dimension.

此外,还有一个小黑客"可以将浮点数放入维度,但警告这是真正的黑客,你有可能失去浮动范围和精度.

Additionally, there is small "hack" to put float number into dimension, but be WARNED that this is really hack, and you are risking chance to lose float range and precision.

<resources>
    <dimen name="text_line_spacing">2.025px</dimen>
</resources>

从代码中,你可以得到那个浮点数

and from code, you can get that float by

float lineSpacing = getResources().getDimension(R.dimen.text_line_spacing);

在这种情况下,lineSpacing 的值是 2.024993896484375,而不是您所期望的 2.025.

in this case, value of lineSpacing is 2.024993896484375, and not 2.025 as you would expected.

这篇关于将浮点值添加到 android 资源/值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆