基础控件类日常总结

一些基础控件的常用方法, 不定期更新

EditText

  • 限制最大输入数,并Toast提示
editText.setFilters(new InputFilter[]{new MaxTextLengthFilter(length, toastStr)});


class MaxTextLengthFilter implements InputFilter {

        int mMaxLength;
        Toast toast;

        MaxTextLengthFilter(int max, String toastStr) {
            mMaxLength = max;
            toast = Toast.makeText(activity, toastStr, Toast.LENGTH_SHORT);
            toast.setGravity(Gravity.CENTER, 0, 0);
        }

        public CharSequence filter(CharSequence source, int start, int end,
                                   Spanned dest, int dstart, int dend) {
            int keep = mMaxLength - (dest.length() - (dend - dstart));
            if (keep < (end - start)) {
                toast.show();
            }
            if (keep <= 0) {
                return "";
            } else if (keep >= end - start) {
                return null;
            } else {
                return source.subSequence(start, start + keep);
            }
        }
    }
  • 进入页面后弹出软键盘
// 曲线救国,进入页面0.5s后(待EditText渲染完成)调出软键盘

        Timer timer = new Timer();
        timer.schedule(new TimerTask() {
            public void run() {
                InputMethodManager inputManager = (InputMethodManager) editText.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
                inputManager.showSoftInput(editText, 0);
            }
        }, 500);

你可能感兴趣的:(基础控件类日常总结)