Android根据文字长度自动调整字号的TextView

自动调整字号的TextView
本文介绍了一种自定义TextView的方法,可以根据文字长度自动调整字号大小和换行显示,确保长标题能够完整展示。通过计算TextView的宽高和文字长度来调整字号。

概述

在项目中遇到需求就是,标题根据文字的长度自动适配字号大小和换行显示,因为标题可能很长然后显示不完全。

实现

根据需求,很容易想到根据TextView的宽高和文字长度计算字号,然后重新设置TextView字号。


/**
 * @author Wastrel
 * @date 创建时间:2016年8月19日 上午9:12:01
 * TODO
 */

import android.content.Context;
import android.text.Layout;
import android.text.StaticLayout;
import android.text.TextPaint;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.util.Log;
import android.util.TypedValue;
public class AutoFitTextView extends android.support.v7.widget.AppCompatTextView {

    private static float DEFAULT_MIN_TEXT_SIZE = 15;
    private static float DEFAULT_MAX_TEXT_SIZE = 50;

    private TextPaint testPaint;
    private float minTextSize;
    private float maxTextSize;

    public AutoFitTextView(Context context, AttributeSet attrs) {
        super(context, attrs);
        initialise();
    }

    private void initialise() {
        testPaint = new TextPaint();
        testPaint.set(this.getPaint());
        // max size defaults to the intially specified text size unless it is
        // too small
        maxTextSize = this.getTextSize();
        if (maxTextSize <= DEFAULT_MIN_TEXT_SIZE) {
            maxTextSize = DEFAULT_MAX_TEXT_SIZE;
        }
        minTextSize = DEFAULT_MIN_TEXT_SIZE;
    }

    /**
     * Re size the font so the specified text fits in the text box
     * assuming the text box is the specified width.
     */
    private void refitText(String text, int textWidth, int textHeight) {
        if (textWidth > 0 && textHeight > 0) {
            //allow diplay rect
            int availableWidth = textWidth - this.getPaddingLeft() - this.getPaddingRight();
            int availableHeight = textHeight - this.getPaddingBottom() - this.getPaddingTop();
            //by the line calculate allow displayWidth
            int autoWidth = availableWidth;
            float mult = getLineSpacingMultiplier();
            float add = getLineSpacingExtra();
            float trySize = maxTextSize;
            testPaint.setTextSize(trySize);
            int lineCount = 1;
            while ((trySize > minTextSize)) {
                StaticLayout layout = new StaticLayout(text, testPaint, autoWidth, Layout.Alignment.ALIGN_NORMAL, mult, add, true);
                int displayH = layout.getHeight();
                if (displayH < availableHeight) {
                    lineCount = layout.getLineCount();
                    break;
                }
                trySize--;
                if (trySize <= minTextSize) {
                    trySize = minTextSize;
                    break;
                }
                testPaint.setTextSize(trySize);
            }
            //setMultiLine
            if (lineCount > 1) {
                this.setSingleLine(false);
                this.setMaxLines(lineCount);
                this.setEllipsize(TextUtils.TruncateAt.END);
            }
            this.setTextSize(TypedValue.COMPLEX_UNIT_PX, trySize);
        }
    }

    @Override
    protected void onTextChanged(CharSequence text, int start, int before, int after) {
        super.onTextChanged(text, start, before, after);
        refitText(text.toString(), this.getWidth(), this.getHeight());
    }

    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        Log.e("TagSizeChange", "new(" + w + "," + h + ") old(" + oldw + "" + oldh + ")");
        if (w != oldw || h != oldh) {
            refitText(this.getText().toString(), w, h);
        }
    }
}

代码注释很详细,具体的请看代码。

效果

布局文件使用:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context="com.example.autofittext.MainActivity">

    <com.example.autofittext.AutoFitTextView
        android:background="#80808080"
        android:layout_width="match_parent"
        android:layout_height="50dp"
        android:textSize="30sp"
        android:gravity="center"
        android:text="@string/str10" />
    <com.example.autofittext.AutoFitTextView
        android:layout_marginTop="15dp"
        android:background="#80808080"
        android:layout_width="match_parent"
        android:layout_height="50dp"
        android:gravity="center"
        android:textSize="30sp"
        android:text="@string/str20"/>


    <com.example.autofittext.AutoFitTextView
        android:layout_marginTop="15dp"
        android:background="#80808080"
        android:layout_width="match_parent"
        android:layout_height="50dp"
        android:gravity="center"
        android:textSize="30sp"
        android:text="@string/str30"/>

    <com.example.autofittext.AutoFitTextView
        android:layout_marginTop="15dp"
        android:background="#80808080"
        android:layout_width="match_parent"
        android:layout_height="50dp"
        android:textSize="30sp"
        android:gravity="center"
        android:text="@string/str40"/>
    <com.example.autofittext.AutoFitTextView
        android:layout_marginTop="15dp"
        android:background="#80808080"
        android:layout_width="match_parent"
        android:layout_height="50dp"
        android:gravity="center"
        android:textSize="30sp"
        android:text="@string/str50"/>
    <com.example.autofittext.AutoFitTextView
        android:layout_marginTop="15dp"
        android:background="#80808080"
        android:gravity="center"
        android:textSize="30sp"
        android:layout_width="match_parent"
        android:layout_height="50dp"
        android:text="@string/str60"/>
    <com.example.autofittext.AutoFitTextView
        android:layout_marginTop="15dp"
        android:background="#80808080"
        android:gravity="center"
        android:textSize="30sp"
        android:layout_width="match_parent"
        android:layout_height="50dp"
        android:text="@string/str70"/>
</LinearLayout>

效果图

后记

  • 使用的时候尽量对TextView的宽高限制。wrap_content 可能达不到想要的效果。
  • 如果想多行的时候左对齐,那么可以在设置多行的时候对Gravity 属性进行设置。
<think>我们被要求解决AndroidTextView在中文和日文文本下高度不一致的问题。 根据引用[1]:文本长度和布局会因语言的不同而产生变化,例如中文和日文可能比英文占用更多的空间。因此,进行布局和文本适配非常关键。 引用[2]展示了一个布局示例,其中使用了wrap_content来适应内容。 引用[3]提到了一键国际化的工具,但这里我们更关注显示问题。 问题分析: 中文和日文属于复杂文字,可能由于字体、行高、字符间距等原因导致相同字号下显示高度不一致。 解决方案: 1. 设置固定的行高(lineHeight)或行间距(lineSpacingExtra)。但注意,固定行高可能导致文本被裁剪,所以可以设置行高最小值并允许扩展。 2. 使用支持多语言的字体,确保在不同语言下字体度量一致。 3. 设置TextView的高度为wrap_content,并设置minHeight(最小高度)属性,确保有足够的高度。 4. 使用ConstraintLayout等灵活布局,避免固定高度。 具体步骤: 方法一:设置固定行高(推荐使用sp单位,可随系统字体缩放) 在XML中,可以设置: android:lineSpacingExtra="Xdp" // 增加额外的行间距 或 android:lineHeight="Xsp" // 设置行高(需要API level 16以上) 但注意,不同语言可能需要不同的行高,所以我们可以为不同语言设置不同的行高值。 方法二:使用尺寸资源适配 在res/values/dimens.xml中定义行高,然后为不同语言创建不同的dimens文件,例如: res/values-zh/dimens.xml // 中文 res/values-ja/dimens.xml // 日文 例如: values/dimens.xml: <dimen name="text_line_height">20sp</dimen> values-zh/dimens.xml: <dimen name="text_line_height">22sp</dimen> values-ja/dimens.xml: <dimen name="text_line_height">22sp</dimen> 然后在TextView中: android:lineHeight="@dimen/text_line_height" 方法三:设置最小高度 android:minHeight="XXdp" android:height="wrap_content" 方法四:使用AppCompatTextView,并确保使用兼容的字体。 另外,我们还可以通过代码动态调整textView.setLineHeight(resources.getDimensionPixelSize(R.dimen.text_line_height)) 注意事项: 1. 避免使用固定高度(例如android:layout_height="50dp"),这样在不同语言下可能显示不全或者留白过多。 2. 测试时,需要在中文和日文环境下分别测试。 示例代码(XML): 假设我们有一个TextView,我们希望它在不同语言下都能保持合适的高度,并且高度一致。 在布局文件中: <TextView android:id="@+id/text_view" android:layout_width="match_parent" android:layout_height="wrap_content" android:minHeight="@dimen/min_text_height" <!-- 设置一个最小高度,确保单行时高度足够 --> android:lineHeight="@dimen/text_line_height" <!-- 设置行高,通过多语言资源适配 --> android:text="@string/hello_world" /> 在res/values/dimens.xml中: <dimen name="min_text_height">40dp</dimen> <dimen name="text_line_height">20sp</dimen> 在res/values-zh/dimens.xml中: <dimen name="text_line_height">22sp</dimen> <!-- 针对中文调整行高 --> 在res/values-ja/dimens.xml中: <dimen name="text_line_height">22sp</dimen> <!-- 针对日文调整行高 --> 这样,在中文和日文环境下,行高被设置为22sp,而其他语言使用20sp。同时,最小高度保证了即使只有一行文本,也有足够的高度。 如果问题仍然存在,可能需要检查字体是否支持这些语言,以及是否在字体文件中包含这些语言的字符。 另外,引用[1]中提到使用ConstraintLayout来处理不同的屏幕尺寸和方向,我们也可以考虑使用更灵活的布局容器。 总结:通过结合使用行高设置、最小高度以及多语言资源适配,可以解决中文和日文文本高度不一致的问题。 生成相关问题: 1. 如何为Android应用添加多语言支持? 2. 如何测试Android应用在不同语言环境下的显示效果? 3. 除了行高,还有哪些属性会影响TextView的显示高度? 4. 如何动态改变应用的语言设置?</think>### Android TextView 中文和日文文本自适应高度设置方法 在 Android 开发中,解决中文和日文文本高度不一致的问题,需结合文本特性、布局管理和资源适配方案。以下是具体解决方案: #### 1. **设置行高和最小高度** 使用 `lineHeight` 属性统一行高,配合 `minHeight` 保证最小高度: ```xml <TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:lineHeight="24sp" <!-- 统一行高 --> android:minHeight="48dp" <!-- 最小高度防截断 --> android:text="@string/multilingual_text"/> ``` **原理**: 中文字符高度通常大于拉丁字母(如英文),通过固定 `lineHeight` 可消除字体差异导致的垂直间距不一致[^1]。 #### 2. **多语言尺寸资源适配** 为不同语言创建专属 `dimens.xml` 资源: 1. 在 `res/values-zh/dimens.xml` 中: ```xml <dimen name="text_line_height">26sp</dimen> <!-- 中文行高 --> ``` 2. 在 `res/values-ja/dimens.xml` 中: ```xml <dimen name="text_line_height">25sp</dimen> <!-- 日文行高 --> ``` 3. 布局中引用: ```xml <TextView android:lineHeight="@dimen/text_line_height" /> ``` **优势**: 精准适配不同语言的字符高度特性,避免一刀切的高度设定[^1][^3]。 #### 3. **动态调整文本高度** 在代码中根据语言动态设置高度: ```java TextView textView = findViewById(R.id.text_view); Configuration config = getResources().getConfiguration(); if (config.locale.getLanguage().equals("zh")) { textView.setLineHeight(spToPx(26)); // 中文行高 } else if (config.locale.getLanguage().equals("ja")) { textView.setLineHeight(spToPx(25)); // 日文行高 } // SP转PX工具方法 private int spToPx(float sp) { return (int) TypedValue.applyDimension( TypedValue.COMPLEX_UNIT_SP, sp, getResources().getDisplayMetrics()); } ``` #### 4. **使用 ConstraintLayout 约束布局** 通过约束关系避免高度塌陷: ```xml <androidx.constraintlayout.widget.ConstraintLayout> <TextView android:id="@+id/text_view" android:layout_width="0dp" android:layout_height="wrap_content" app:layout_constraintTop_toTopOf="parent" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintHeight_min="48dp" /> <!-- 最小高度约束 --> </androidx.constraintlayout.widget.ConstraintLayout> ``` **效果**: `wrap_content` 高度自适应内容,`constraintHeight_min` 防止短文本高度不足[^1][^2]。 #### 5. **启用字体回退机制** 在 `res/font` 中创建字体族,确保生僻字符显示正常: ```xml <font-family xmlns:android="http://schemas.android.com/apk/res/android"> <font android:font="@font/noto_sans_sc" /> <!-- 简体中文 --> <font android:font="@font/noto_sans_jp" /> <!-- 日文 --> <font android:font="@font/roboto" /> <!-- 默认回退 --> </font-family> ``` **作用**: 避免因缺字导致的文本高度计算错误(推荐使用 Noto Sans 系列字体)。 --- ### 关键注意事项 1. **禁止固定高度**: 绝对高度(如 `android:layout_height="50dp"`)会导致长文本截断或短文本留白。 2. **测试工具建议**: - 使用 Android Studio 的 **Layout Inspector** 检查渲染高度 - 通过 **开发者选项** 快速切换系统语言 - 利用 `tools:locale` 属性预览多语言布局: ```xml <TextView tools:locale="ja_JP" <!-- 预览日文效果 --> tools:text="@string/japanese_sample" /> ``` 3. **性能优化**: 避免在 `ListView/RecyclerView` 中频繁计算高度,应在 `ViewHolder` 中缓存高度配置。 ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值