【问题标题】:Android - Text size the same across all screen sizesAndroid - 所有屏幕尺寸的文本大小相同
【发布时间】:2016-08-11 02:54:36
【问题描述】:

在我的 Android 应用中,我有以下布局:

<android.support.v7.widget.CardView
        android:id="@+id/difficultyCardView"
        app:layout_widthPercent="60%"
        android:layout_height="wrap_content"
        android:layout_marginTop="8dp"
        app:cardUseCompatPadding="true"
        android:layout_centerHorizontal="true"
        android:layout_above="@+id/noHighScoresCardView">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:background="@color/yellow"
            android:orientation="vertical">

            <ImageView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_gravity="center_horizontal"
                android:layout_marginBottom="10dp"
                android:src="@drawable/pushpin" />

            <TextView
                android:id="@+id/diffNameTv"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_gravity="center_horizontal"
                android:layout_marginBottom="12dp"
                android:maxLines="1"
                android:singleLine="true"
                android:text="FÁCIL"
                android:textSize="20sp"
                android:textStyle="bold" />

        </LinearLayout>
    </android.support.v7.widget.CardView>

在我的 Nexus 5 中,如上所示将文本大小设置为 20sp,使文本占据 CardView 宽度的大约 75%。问题是,当我在较小的手机上进行测试时,它会在文本中添加省略号。

我想要实现的是,在每个屏幕尺寸和分辨率上,文本都将准确占据卡片的 75%。

那么,我该如何解决这个问题,创建多个比例文件夹(ldpi、mdpi、...)并调整每个文件夹的字体大小、通过代码以百分比计算它,或任何其他解决方案?

谢谢。

【问题讨论】:

    标签: android textview


    【解决方案1】:

    获取特定设备上的卡片宽度并乘以 0.75,然后将文本大小设置为该值。

    【讨论】:

      【解决方案2】:

      如果您希望 textview 占用 75% 的 cardview 且 textsize 为 20sp,那么文本将溢出到多行中。

      android:maxLines="1"
      android:singleLine="true"
      

      删除这些不需要的属性并允许多行文本视图

      【讨论】:

        【解决方案3】:

        文字总是一样吗?如果是这样,解决方案就很简单了。

        int ratio = 15;
        int width = difficultyCardView.getWidth();
        diffNameTv.setTextSize(width/ratio);
        

        调整比例直到你想要的大小,那么无论屏幕大小,文字与卡片的相对大小都是相同的。

        【讨论】:

        • 我的应用程序已本地化为西班牙语和英语,因此文本不会总是相同。
        【解决方案4】:

        您要做的是创建响应式布局。为此,请在 res 目录中创建其他布局文件夹。在文件夹名称的末尾添加像素密度名称,使用破折号分隔文本“布局”和密度(例如 layout-hdpi、layout-mhdpi、layout-xhdpi 等)。在这些文件夹中,创建所需的布局对于每个密度。然后,您可以根据像素密度将 textview 的大小调整为每个不同屏幕尺寸的 75%。因此,如果 20sp 填充了 hdpi 布局的 75%,那么您可能需要增加 mhdpi 的文本大小以填充卡片的 75%。

        Android 会根据屏幕尺寸自动为特定设备选择正确的布局。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2015-05-11
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2017-05-20
          相关资源
          最近更新 更多