我试图添加一个小的行之间的空间到我的TextViews使用android:lineSpacingMultiplier 从文档中可以看到:

文本行与行之间的额外间距, 作为乘数。 必须是浮点值,比如 “1.2”。

因为我使用这在几个不同的TextViews,我想添加一个全局维度/值到我的资源,但我不知道使用哪个标签,如果它甚至存在。 我尝试了所有对我有意义的资源类型,但没有一个有用。

我想要的是这样的:

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

编辑:我知道android:lineSpacingExtra(需要一个附加单位的维度),但我想使用android:lineSpacingMultiplier如果可能的话。


当前回答

我们也可以用它作为约束布局的指导原则。

创建integer.xml文件并添加到

 <item name="guideline_button_top" type="integer" format="float">0.60</item>

从layout.xml文件中使用

 app:layout_constraintGuide_percent="@integer/guideline_button_top" 

其他回答

有一个解决方案:

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

通过这种方式,您的浮点数将在@dimen下面。注意,你可以使用其他“format”和/或“type”修饰符,其中format代表:

Format =封闭数据类型:

浮动 布尔 分数 整数 ...

type代表:

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

颜色 dimen 字符串 风格 等等……

要从代码中获取资源,你应该使用下面的代码片段:

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

我知道这是令人困惑的(你会期望调用像getResources(). getdimension (r.d I d .text_line_spacing)),但Android维度有特殊的处理和纯粹的“浮动”数字不是有效的维度。


此外,有一个小的“黑客”把浮动数变成维度,但要警告,这是真正的黑客,你有机会失去浮动范围和精度。

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

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

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

在本例中,linespace的值是2.024993896484375,而不是您所期望的2.025。

我还发现了一个没有警告的变通方法:

<resources>
    <item name="the_name" type="dimen">255%</item>
    <item name="another_name" type="dimen">15%</item>
</resources>

然后:

// theName = 2.55f
float theName = getResources().getFraction(R.dimen.the_name, 1, 1);
// anotherName = 0.15f
float anotherName = getResources().getFraction(R.dimen.another_name, 1, 1);

警告:它只在从Java代码中使用dimen而不是从xml中使用dimen时有效

在dimensions .xml中添加一个浮点数:

<项目格式=“浮点数” 名称=“my_dimen” 类型=“dimen”>1.2</item>

从XML引用:

<EditText 
    android:lineSpacingMultiplier="@dimen/my_dimen"
    ...

要以编程方式读取这个值,可以使用ResourcesCompat。getFloat从androidx.core

Gradle依赖性:

实现(“androidx.core:核心:$ {version}”)

用法:

import androidx.core.content.res.ResourcesCompat;

...

float value = ResourcesCompat.getFloat(context.getResources(), R.dimen.my_dimen);

float或double形参可以存储为字符串:

<resources>
    <string name="x">0.01</string>
</resources>

然后得到:

double value = Double.parseDouble(this.getString(R.string.x));

如果你想把x解析为浮点数,请使用java.lang.Float.parseFloat()。

如果您有控制范围的简单浮点数,您也可以在资源中使用一个整数,并在代码中直接除以所需的小数点后数位。

就像这样

<integer name="strokeWidth">356</integer>

小数点后2位

this.strokeWidthFromResources = resources_.getInteger(R.integer.strokeWidth);    
circleOptions.strokeWidth((float) strokeWidthFromResources/ 100);

所以是3.56f

并不是说这是最优雅的解决方案,但对于简单的项目来说,它很方便。