欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

解决Android TextView中英文混排换行问题

程序员文章站 2022-06-13 22:47:44
...

个人极不建议这样做(之后会说原因)

1 现象

解决Android TextView中英文混排换行问题
绿色底黄色框内的就是原生TextView出现的情况,出现这种情况的主要原因就是分词问题。TextView会认为英文字符在没有空格给开的时候是一个完整的单词(它不局限于字母,也可能不是个单词)在当前行展示不下且在下一行能完整展示的时候,就会出现这种情况。

2 解决思路

手动计算TextView每行能展示多少个字符,手动进行分行(在末尾加空字符或者换行符均可)。

AutoWrapTextView代码:

/**
 * @author KaraShokZ
 * DESCRIPTION 解决中英文混排,自动折行问题
 * @name AutoWrapedTextView
 **/
public class AutoWrapTextView extends AppCompatTextView {

    public AutoWrapTextView(@NonNull Context context) {
        super(context);
    }

    public AutoWrapTextView(@NonNull Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
    }

    public AutoWrapTextView(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    /**
     * 手动计算TextView每行能展示多少字符,并分行
     * @param charSequence 目标文本
     * @return
     */
    public String splitText(CharSequence charSequence) {
        if (TextUtils.isEmpty(charSequence)) return "";
        List<StringBuilder> splitTextList = new ArrayList<>();
        int singleTextWidth = getMeasuredWidth() - getPaddingLeft() - getPaddingRight(); // TextView 每行的宽度
        int currentSingleTextWidth = 0; // 用来叠加字符的宽度
        StringBuilder lineStringBuffer = new StringBuilder();
        for (int i = 0, length = charSequence.length(); i < length; i++) {
            char textChar = charSequence.charAt(i);
            currentSingleTextWidth += getSingleCharWidth(textChar);
            if (currentSingleTextWidth > singleTextWidth) {// 当字符宽度大于 TextView 的宽度时,需要折行
                lineStringBuffer.append(" ");// 末尾加空字符,会强行分词
                splitTextList.add(lineStringBuffer);
                lineStringBuffer = new StringBuilder();
                currentSingleTextWidth = 0;
                i--;
            } else {
                lineStringBuffer.append(textChar);
                if (i == length - 1) splitTextList.add(lineStringBuffer);
            }
        }

        StringBuilder splitSb = new StringBuilder();
        int maxLines = getMaxLines();
        boolean hasMore = splitTextList.size() > maxLines;
        if (hasMore){// 当所需行数大于最大行数时,手动截取
            splitTextList = splitTextList.subList(0,maxLines);
        }
        for (StringBuilder stringBuilder : splitTextList){
            splitSb.append(stringBuilder);
        }
        if (hasMore){// 当所需行数大于最大行数时,最后一行手动省略末尾(这个只适用于 ellipsize=end)
            int length = splitSb.length();
            String three_dots = "...";
            splitSb.replace(length - three_dots.length() + 1,length - 1,three_dots);
        }
        return splitSb.toString();

    }

    /**
     * 计算每个字符的宽度
     * @param textChar 待计算的字符
     * @return
     */
    private float getSingleCharWidth(char textChar) {
        float[] width = new float[1];
        getPaint().getTextWidths(new char[] {textChar}, 0, 1, width);
        return width[0];
    }
}

使用:

class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        val str1 = getText("abcdefghijklm")
        exploreSpannableEllipsizeTextView1.setMovementMethod(FilterLinkMovementMethod())
        exploreSpannableEllipsizeTextView1.setHighlightColor(this.getResources().getColor(R.color.white))
        exploreSpannableEllipsizeTextView1.setText(str1)

        val str2 = getText("abcdefghijklmnopqrstuvwxyzabcdefghijklmnop")
        exploreSpannableEllipsizeTextView2.setMovementMethod(FilterLinkMovementMethod())
        exploreSpannableEllipsizeTextView2.setHighlightColor(this.getResources().getColor(R.color.white))
        exploreSpannableEllipsizeTextView2.setText(str2)

        val str3 = getText("abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnop")
        exploreSpannableEllipsizeTextView3.setMovementMethod(FilterLinkMovementMethod())
        exploreSpannableEllipsizeTextView3.setHighlightColor(this.getResources().getColor(R.color.white))
        exploreSpannableEllipsizeTextView3.setText(str3)

        autoWrapTextView1.setMovementMethod(FilterLinkMovementMethod())
        autoWrapTextView1.setHighlightColor(this.getResources().getColor(R.color.white))
        autoWrapTextView1.post {
            val str11 = autoWrapTextView1.splitText(str1)
            autoWrapTextView1.setText(getText1(str11))
        }

        autoWrapTextView2.setMovementMethod(FilterLinkMovementMethod())
        autoWrapTextView2.setHighlightColor(this.getResources().getColor(R.color.white))
        autoWrapTextView2.post {
            val str22 = autoWrapTextView2.splitText(str2)
            autoWrapTextView2.setText(getText1(str22))
        }

        autoWrapTextView3.setMovementMethod(FilterLinkMovementMethod())
        autoWrapTextView3.setHighlightColor(this.getResources().getColor(R.color.white))
        autoWrapTextView3.post {
            val str33 = autoWrapTextView3.splitText(str3)
            autoWrapTextView3.setText(getText1(str33))
        }
    }

    fun getText(content: String) : SpannableString {
        var activityName: String  = "#是的冯绍峰#"

        var contentStrB: StringBuilder = StringBuilder(activityName)
        contentStrB.append(content)
        var spannableString: SpannableString = SpannableString(contentStrB.toString())
        var colorSpan: ForegroundColorSpan = ForegroundColorSpan(this.getResources().getColor(R.color.color_3AA2E1));
        spannableString.setSpan(colorSpan, 0,activityName.length, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        var clickableSpan: ExploreContentActivityIntentClickableSpan  = ExploreContentActivityIntentClickableSpan("111");
        spannableString.setSpan(clickableSpan, 0, activityName.length, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        return spannableString
    }

    fun getText1(content: String) : SpannableString {
        var activityName: String  = "#是的冯绍峰#"

        var spannableString: SpannableString = SpannableString(content)
        var colorSpan: ForegroundColorSpan = ForegroundColorSpan(this.getResources().getColor(R.color.color_3AA2E1));
        spannableString.setSpan(colorSpan, 0,activityName.length, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        var clickableSpan: ExploreContentActivityIntentClickableSpan  = ExploreContentActivityIntentClickableSpan("111");
        spannableString.setSpan(clickableSpan, 0, activityName.length, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        return spannableString
    }

}

3不推荐的原因

主要有两点:
1、这样会破坏纯英文下的分词,也就是正常情况下当末尾端的英文单词展示不下时,系统会把它折到下一行去。这样的强行干扰会破坏此机制,末尾端的单词可能会被折断。
2、大家可以看到这个计算其实还是有点消耗性能的,就位了这么一点点的所谓的美观,其实有些不值当。因为像微信、微博等都没有处理这种情况。可见这个所谓的优化其实是有点画蛇添足的(当然,产品大大要求除外)。

所以,这里不推荐各位小主去处理这种东西。当然,如果真有这种需求的话,希望可以给小主提供一个思路。