Android源碼計算機:當輸入到一定數,加減乘除一些數後,容易報錯。
2. 想在計算機的數字輸入框中,加入限制最大輸入數並提示。
用如下方法本來可以很輕意地解決此問題 ,但由於布局運用到了:CalculatorDisplay,其extends了ViewSwitcher,在lengthFilter 需要用到參數:EditText,即輸入框。由於對android源碼計算機不熟,一時不知如何擷取計算機輸入框,後來發現通過CalculatorDisplay的getChildAt(1)可以取得。在onCreate調用如下lengthFilter方法,如:lengthFilter(this,(EditText)mDisplay.getChildAt(1),50,getResources().getString(R.string.most_char)); 可以解決
- public static void lengthFilter(final Context context, final EditText editText, final int max_length, final String err_msg) {
-
- InputFilter[] filters = new InputFilter[1];
-
- filters[0] = new InputFilter.LengthFilter(max_length) {
-
- @Override
- public CharSequence filter(CharSequence source, int start, int end,
- Spanned dest, int dstart, int dend) {
- // TODO Auto-generated method stub
-
- int destLen = getCharacterNum(dest.toString()); //擷取字元個數(一個中文算2個字元)
- int sourceLen = getCharacterNum(source.toString());
- if (destLen + sourceLen > max_length) {
- Toast.makeText(context, err_msg,Toast.LENGTH_SHORT).show();
- return "";
- }
- return source;
-
- }
-
- };
-
- editText.setFilters(filters);
-
- }
-
- /**
- * @description 擷取一段字串的字元個數(包含中英文,一個中文算2個字元)
- * @param content
- * @return
- */
- public static int getCharacterNum(final String content) {
- if (null == content || "".equals(content)) {
- return 0;
- }else {
- return (content.length() + getChineseNum(content));
- }
- }
-
-
-
-
- /**
- * @description 返回字串裡中文字或者全形字元的個數
- * @param s
- * @return
- */
- public static int getChineseNum(String s) {
-
- int num = 0;
- char[] myChar = s.toCharArray();
- for (int i = 0; i < myChar.length; i++) {
- if ((char)(byte)myChar[i] != myChar[i]) {
- num++;
- }
- }
- return num;
- }