package com.rv.component.utils;

import android.content.Context;
import android.text.Editable;
import android.text.Selection;
import android.text.TextWatcher;
import android.util.Log;
import android.widget.EditText;
import android.widget.Toast;

public class MyTextWatcher implements TextWatcher {
    private Context context;

    private EditText editText;

    private int len; //允许输入的字节长度(一个中文占3个字节)

    public MyTextWatcher(Context context, EditText editText, int len) {
        this.context = context;
        this.editText = editText;
        this.len = len;
    }

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {

    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {

    }

    @Override
    public void afterTextChanged(Editable editable) {
        String inputStr = editable.toString().trim();
        byte[] bytes = inputStr.getBytes();
        if (bytes.length > len) {
            Toast.makeText(context, "超过规定字符数", Toast.LENGTH_SHORT).show();
            Log.i("str", inputStr);
            //取前15个字节
            byte[] newBytes = new byte[len];
            for (int i = 0; i < len; i++) {
                newBytes[i] = bytes[i];
            }
            String newStr = new String(newBytes);
            editText.setText(newStr);
            //将光标定位到最后
            Selection.setSelection(editText.getEditableText(), newStr.length());
        }
    }
}
