【问题标题】:Android: Different style (textSize) for different layout sizesAndroid:不同布局大小的不同样式(textSize)
【发布时间】:2016-09-15 06:50:10
【问题描述】:

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

<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 改变的 noew 样式。

<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

【问题讨论】:

    标签: android android-layout


    【解决方案1】:

    是的,这是可能的。这是您可以安排的方式。在你默认的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>
    

    P.s.,字体使用sp。和dp一样,只是如果用户通过系统设置增加默认字体大小,你的字体会相应改变。

    【讨论】:

      【解决方案2】:

      先准备好这样的文件:

      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>
      

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

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

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

      【讨论】:

      • 屏幕尺寸与 DPI 无关。您可以拥有 mdpi(1280x800 10" 平板电脑)或 xhdpi(2560x1600 10" 平板电脑)的 xlarge 屏幕。
      • @JeffreyBlattman 好的,谢谢您的信息。我有一个疑问,如果我有一个按钮,我想为dimens.xml 的不同分辨率指定它的大小,那么使用什么来代替DPI
      • 这个问题很复杂。过去你会使用屏幕尺寸类:小、正常、大和 xlarge。现在不推荐使用大小限定符:developer.android.com/guide/practices/…
      猜你喜欢
      • 1970-01-01
      • 2021-11-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多