TextView不同长度文本对齐

展示效果:


image.png
/**
 * 将给定的字符串给定的长度两端对齐
 *
 * @param str 待对齐字符串
 * @param size 汉字个数,eg:size=5,则将str在5个汉字的长度里两端对齐
 * @param isAddColon 是否添加冒号
 * @return 调整后的字符串
 */
public static SpannableStringBuilder justifyString(String str, int size, boolean isAddColon) {
    SpannableStringBuilder spannableStringBuilder = new SpannableStringBuilder();
    if (TextUtils.isEmpty(str)) {
        return spannableStringBuilder;
    }
    char[] chars = str.toCharArray();
    if (chars.length >= size || chars.length == 1) {
        spannableStringBuilder.append(str);
        if (isAddColon){
            spannableStringBuilder.append(":");
        }
        return spannableStringBuilder;
    }
    int l = chars.length;
    float scale = (float) (size - l) / (l - 1);
    for (int i = 0; i < l; i++) {
        spannableStringBuilder.append(chars[i]);
        if (i != l - 1) {
            // 全角空格;
            SpannableString s = new SpannableString(" ");
            s.setSpan(new ScaleXSpan(scale), 0, 1, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
            spannableStringBuilder.append(s);
        }
    }
    if (isAddColon){
        spannableStringBuilder.append(":");
    }
    return spannableStringBuilder;
}

你可能感兴趣的:(TextView不同长度文本对齐)