給文字控制元件設定字數限制並優化toast彈窗
阿新 • • 發佈:2021-01-14
前言
這裡使用的是安卓提供的InputFilter給輸入框新增限制,如果不需要給輸入提示的話,可以直接使用;例如:給editText新增一個輸入限制最高為30,直接這樣寫
editText.setFilters(new InputFilter[]{new InputFilter.LengthFilter(30)});
實現InputFilter
示例:
import android.content.Context; import android.graphics.Color; import android.graphics.PorterDuff; import android.text.InputFilter; import android.text.Spanned; import android.view.Gravity; import android.widget.Toast; public class MyLengthFilter implements InputFilter { private final int mMax; private Context context; public MyLengthFilter(int max, Context context) { mMax = max; this.context = context; } public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) { int keep = mMax - (dest.length() - (dend - dstart)); if (keep <= 0) { //這裡,用來給使用者提示 Toast toast = Toast.makeText(context, "字數不能超過" + mMax, Toast.LENGTH_SHORT); // 原吐司背景不明顯,修改背景色 toast.getView().getBackground().setColorFilter(Color.parseColor("#c9c9c9"), PorterDuff.Mode.DARKEN); // 調整吐司位置,在螢幕中間顯示 toast.setGravity(Gravity.CENTER, 0, 0); toast.show(); return ""; } else if (keep >= end - start) { return null; // keep original } else { keep += start; if (Character.isHighSurrogate(source.charAt(keep - 1))) { --keep; if (keep == start) { return ""; } } return source.subSequence(start, keep); } } }
使用程式碼如下 :
//新增字數限制
mEditText.setFilters(new InputFilter[]{new MyLengthFilter(35,context)});