天天看点

Android限制字符显示 超过字符数减少2字符以...结尾

前几天程序员跟产品干架视频太火了,仔细想想,某些需求,真的有点不大合理,这是我们公司的一个。

需求:

最多显示8个字符(四个中文汉字或8个英文字母);
* 当超过四个汉字或8个英文字母,则显示【三个汉字+…】或【6个英文字母+…】,eg:张雨涵、欧阳娜娜、蔡文玉…、张雨john、张宇mk…、shizhi…;      

实现如下:

valus里的attr 

<declare-styleable name="StudentNameTextView">
    <attr name="max_num"  format="integer" />
</declare-styleable>      

然后写个自定义的Textview

public class StudentNameTextView extends AppCompatTextView {

    private String originalText;
    /**
     * 最大字符个数
     */
    private int maxNum ;

    public StudentNameTextView(Context context) {
        this(context, null);
    }

    public StudentNameTextView(Context context, @Nullable AttributeSet attrs) {
        this(context, attrs, 0);
    }

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

    private void init(Context context, AttributeSet attrs, int defStyleAttr) {
        TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.StudentNameTextView,
                defStyleAttr, 0);
        maxNum = a.getInt(R.styleable.StudentNameTextView_max_num, 8);
        a.recycle();
        originalText = super.getText().toString();
        applyLetter();
    }

    private void applyLetter() {
        String tempText = handleText(originalText, maxNum);
        super.setText(tempText, BufferType.SPANNABLE);
    }

    public String handleText(String str, int maxLen) {
        if (TextUtils.isEmpty(str)) {
            return str;
        }
        int count = 0;
        int endIndex = 0;
        for (int i = 0; i < str.length(); i++) {
            char item = str.charAt(i);
            if (item < 128) {
                //非汉字
                count += 1;
            } else {
                //汉字算两个字符
                count += 2;
            }

            //是否达到最大字符数
            boolean hasExtal = (i < str.length() - 1) && count == maxLen;

            if (hasExtal || count > maxLen) {
                //超过限制
                if (str.charAt(i) < 128) {
                    // 如果是英文不需要当前那个字和前一个字
                    endIndex = i - 1;
                } else {
                    //如果是汉字不需要当前那个字
                    endIndex = i;
                }
                return str.substring(0, endIndex) + "...";
            }

        }
        return str;
    }


    @Override
    public void setText(CharSequence text, BufferType type) {
        originalText = text.toString();
        applyLetter();
    }

    @Override
    public CharSequence getText() {
        return originalText;
    }
}