Android:不同的布局大小(textSize)需要不同的样式

5

我已经为大屏幕上的所有文本按钮制作了自定义样式

<style name="button_large" parent="@android:style/Widget.TextView">
    <item name="android:textColor">@color/button_color</item>
    <item name="android:textSize">30dp</item>
    <item name="android:clickable">true</item>
    <item name="android:soundEffectsEnabled">false</item>
</style>

现在我希望在普通屏幕上使用更小的按钮,并且我添加了一个新样式,只改变了android:textSize。
<style name="button_normal" parent="@android:style/Widget.TextView">
    <item name="android:textColor">@color/button_color</item>
    <item name="android:textSize">10dp</item>
    <item name="android:clickable">true</item>
    <item name="android:soundEffectsEnabled">false</item>
</style>

是否可以根据屏幕大小提取该值并接收所需的值?并仅使用一个样式。

  <item name="android:textSize">value_based_on_screen_size</item>

对于大屏幕,它将是30,对于普通屏幕,它将是10。

2个回答

10

是的,这是可能的。以下是您可以如何安排它的方式。在您的默认values/styles.xml中有:

<style name="button" parent="@android:style/Widget.TextView">
    <item name="android:textColor">@color/button_color</item>
    <item name="android:textSize">@dimen/button_text_size</item>
    <item name="android:clickable">true</item>
    <item name="android:soundEffectsEnabled">false</item>
</style>

那么创建一个像这样的 values/dimens.xml 文件,
<resources>
    <dimen name="button_text_size">10sp</dimen>
</resources>

并创建一个像这样的 values-large

<resources>
    <dimen name="button_text_size">30sp</dimen>
</resources>

提示:使用sp来设置字体大小。与dp非常相似,但如果用户通过系统设置增加默认字体大小,您的字体也会相应更改。


1
首先准备这样的文件:
res/values-ldpi/dimens.xml
res/values-mdpi/dimens.xml
res/values-hdpi/dimens.xml

然后为不同的文件声明资源值:
<!-- in values-ldpi/dimens.xml -->
<dimen name="mytextSize">30dp</dimen>

"and"
<!-- in values-mdpi/dimens.xml -->
<dimen name="mytextSize">20dp</dimen>

然后,在你的样式中使用这种方式:

<item name="android:textSize">@dimen/mytextSize</item>

屏幕尺寸与DPI无关。您可以拥有xlarge屏幕,它们可以是mdpi(1280x800 10英寸平板电脑)或xhdpi(2560x1600 10英寸平板电脑)。 - Jeffrey Blattman
@JeffreyBlattman 好的,谢谢您提供的信息。我有一个问题,如果我有一个按钮,并且我想为不同分辨率从dimens.xml指定其大小,那么我应该使用什么代替DPI - Pratik Sharma
问题很复杂。以前你会使用屏幕尺寸类别:小、正常、大和超大。现在已经弃用了这种方法,改为使用尺寸限定符:http://developer.android.com/guide/practices/screens_support.html#DeclaringTabletLayouts - Jeffrey Blattman

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接