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

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

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

我想要的是这样的:

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

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


当前回答

在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);

其他回答

如此链接所述http://droidista.blogspot.in/2012/04/adding-float-value-to-your-resources.html

在dimension .xml中声明

<item name="my_float_value" type="dimen" format="float">9.52</item>

从xml引用

@dimen/my_float_value

从java引用

TypedValue typedValue = new TypedValue();
getResources().getValue(R.dimen.my_float_value, typedValue, true);
float myFloatValue = typedValue.getFloat();

在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);

如果有人对“欺骗系统”感兴趣,当你被允许只给出特定类型的xml值时,特别是在android布局格式化中使用xml值作为嵌入权重时,你可以这样做:

    <item name="actvity_top_panel_weight" format="float" type="integer">1.5</item>

上面的xml值类似于浮点数,但被称为整数。

然后你可以像下面这样毫无问题地使用它:

        <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="@integer/actvity_top_panel_weight"
        android:orientation="horizontal"></LinearLayout>

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

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

然后得到:

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

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

虽然我在过去使用了公认的答案,但似乎使用当前的构建工具可以做到:

   <dimen name="listAvatarWidthPercent">0.19</dimen>

我使用的是Build Tools主要版本29。