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

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

问题描述

我试图线之间加一点空间来使用我TextViews 安卓lineSpacingMultiplier 从<一个href="http://developer.android.com/reference/android/widget/TextView.html#attr_android%3alineSpacingMultiplier">documentation:

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>

编辑:我知道的机器人:lineSpacingExtra (这需要一个维度附加一个单位),但我想用机器人: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:

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

和类型代表:

类型=资源类型:

  • 颜色
  • 字符串
  • 风格
  • 等等...

要获取从code的资源,你应该使用这个片段:

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 尺寸有特殊的待遇和纯粹的漂浮号是无效的尺寸。

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.

此外,有小黑客将浮点数为维度,但要的警告这是真正破解,然后你冒着机会输浮动范围和precision。

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>

和从code,您可以通过

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天全站免登陆