微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

Android TextView 不会用多行紧紧拥抱文本,而是坚持使用 maxWidth

如何解决Android TextView 不会用多行紧紧拥抱文本,而是坚持使用 maxWidth

我正在创建一个聊天气泡,我注意到当你有一个文本跨多行的 TextView 时,框的宽度锁定到(在这种情况下)maxWidth。这可能会导致右侧出现间隙:

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:maxWidth="100dp"
        android:padding="4dp"
        android:text="this is a pretty short sentence"/>

big right gap

如您所见,右侧有一个很大的白色间隙。没有 maxWidth 它适合在一条线上并且紧贴:

snug fit

如何使文本跨越多行时,框仍然紧紧地拥抱文本?我尝试了很多东西,但这可能吗?

预期结果:

desired result

更新:

android:justificationMode="inter_word"

导致文本适合框而不是框适合文本,这更丑:

inter_word t

解决方法

事实证明,通过继承 TextView 和覆盖 onMeasure() 很容易修复。它甚至适用于布局编辑器。性能也完全没有问题:

@Override
protected void onMeasure(int widthMeasureSpec,int heightMeasureSpec) {
    //call super first so you can call getLineCount(),getLineMax()) and getMeasuredHeight() below
    super.onMeasure(widthMeasureSpec,heightMeasureSpec);

    //if more than 1 line set width equal to that of the largest line
    int lineCount = getLayout().getLineCount();
    if (lineCount > 1) {
        //get the width of the largest line
        float lineWidth = 0;
        for (int i = 0; i < lineCount; i++) {
            lineWidth = Math.max(lineWidth,getLayout().getLineMax(i));
        }
        //set largest line width + horizontal padding as width and keep the height the same
        setMeasuredDimension((int) Math.ceil(lineWidth) + getPaddingLeft() + getPaddingRight(),getMeasuredHeight());
    }
}
,

在 TextView XML 中,您可以使用:

android:justificationMode="inter_word"

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。