Android EditText
阿新 • • 發佈:2018-12-19
-
EditText
EditeText設定它被選中可輸入 跟不被選中不可輸入的時候。 有三個屬性處理
//設定是否能被點選
//這是最重要的,設定不可輸入不可點選直接設定這個屬性就可以
//大坑 只設置enable就可以了 千萬別設定其它的屬性類似focusable
//會導致再按一次沒反應的
editText.setEnabled(false);
editText.setFocusable(true);//能否被聚焦
editText.requestFocus();//請求聚焦
在佈局中直接新建EditText參考下面的屬性
//這個是準備設定它在父佈局的位置跟空間的 LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams (ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT); layoutParams.setMargins(6, 6, 6, 0); editText.setInputType(InputType.TYPE_TEXT_FLAG_MULTI_LINE); //這個是設定它在父佈局的屬性的 editText.setLayoutParams(layoutParams); editText.setId(i); editText.setSingleLine(false); editText.setBackground(getActivity().getDrawable(R.drawable.bg_edit_question)); editText.setTextColor(getActivity().getColor(R.color.white)); editText.setEnabled(false); //豎直方向可以滑動 editText.setVerticalScrollBarEnabled(true); editText.setPadding(10, 4, 4, 4); editText.setGravity(Gravity.TOP); editText.setTextSize(16); //這個要注意一下:設定最大的字數,因為沒有setLength這個屬性 裡面只有這個設定屬性 editText.setFilters(new InputFilter[]{new InputFilter.LengthFilter(500)});
設定只能輸入金額
//在xml中要設定一下屬性
android:inputType="numberDecimal"
//在程式碼中就直接用
InputFilter[] filters={new CashierInputFilter()};
mTextViewSingleGoodsMoney.setFilters(filters); //設定金額輸入的過濾器,保證只能輸入金額型別
/** * Create by ldr * on 2018/8/28 11:31. * 用於在EditeText中增加過濾器 用於控制只能輸入金額 */ public class CashierInputFilter implements InputFilter { Pattern mPattern; //輸入的最大金額 private static final int MAX_VALUE = Integer.MAX_VALUE; //小數點後的位數 private static final int POINTER_LENGTH = 2; private static final String POINTER = "."; private static final String ZERO = "0"; public CashierInputFilter() { mPattern = Pattern.compile("([0-9]|\\.)*"); } @Override public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) { String sourceText = source.toString(); String destText = dest.toString(); //驗證刪除等按鍵 if (TextUtils.isEmpty(sourceText)) { return ""; } Matcher matcher = mPattern.matcher(source); //已經輸入小數點的情況下,只能輸入數字 if(destText.contains(POINTER)) { if (!matcher.matches()) { return ""; } else { if (POINTER.equals(source.toString())) { //只能輸入一個小數點 return ""; } } //驗證小數點精度,保證小數點後只能輸入兩位 int index = destText.indexOf(POINTER); int length = dend - index; if (length > POINTER_LENGTH) { return dest.subSequence(dstart, dend); } } else { /** * 沒有輸入小數點的情況下,只能輸入小數點和數字 * 1. 首位不能輸入小數點 * 2. 如果首位輸入0,則接下來只能輸入小數點了 */ if (!matcher.matches()) { return ""; } else { if ((POINTER.equals(source.toString())) && TextUtils.isEmpty(destText)) { //首位不能輸入小數點 return ""; } else if (!POINTER.equals(source.toString()) && ZERO.equals(destText)) { //如果首位輸入0,接下來只能輸入小數點 return ""; } } } //驗證輸入金額的大小 double sumText = Double.parseDouble(destText + sourceText); if (sumText > MAX_VALUE) { return dest.subSequence(dstart, dend); } return dest.subSequence(dstart, dend) + sourceText; } }