Everyone is not new to Edittext. I won't say much here. I'll go straight to the topic. I'm just writing this article to record some tips for using Edittext:
1. Limit input range method 1:
/** * Limit the range of input numbers */ public class RegionNumberEditText extends EditText { private Context context; private int max; private int min; public RegionNumberEditText(Context context) { super(context); this.context = context; } public RegionNumberEditText(Context context, AttributeSet attrs) { super(context, attrs); this.context = context; } public RegionNumberEditText(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); this.context = context; } /** * Set the range of input numbers * @param maxNum Maximum number * @param minNum Minimum */ public void setRegion(int maxNum, int minNum) { setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_VARIATION_NORMAL); this.max = maxNum; this.min = minNum; } public void setTextWatcher() { addTextChangedListener(new TextWatcher() { @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { if (start >= 0) {//Judging from the first input, if (min != -1 && max != -1) { try { int num = Integer.parseInt(s.toString()); //Determine whether the number in the current EditText (there may be a number in the EditText at the beginning) is greater than max if (num > max) { s = String.valueOf(max);//If greater than max, the content is Max setText(s); Prompt.showTips(context, "Amount cannot exceed" + max + "element"); } else if (num < min) { s = String.valueOf(min);//If less than min, the content is min } } catch (NumberFormatException e) { LFLog.e("ontextchanged", "==" + e.toString()); } //If the number in edittext is between max and min, it will be displayed normally without processing. return; } } } @Override public void afterTextChanged(Editable s) { } }); } }
Call:
RegionNumberEditText edittext=new RegionNumberEditText(this); edittext.setRegion(100,0); edittext.setTextWatcher();
2. Limit the input range method 2:
public class EditInputFilter implements InputFilter{ /** * Maximum number */ public static final int MAX_VALUE = 10000; /** * Number of digits after decimal point */ public static final int PONTINT_LENGTH = 2; Pattern p; public EditInputFilter(){ p = Pattern.compile("[0-9]*"); //Other than numbers } /** * source New input string * start The starting subscript of the new input string, generally 0 * end The subscript of the end of the new input string, generally source length-1 * dest Enter the text box before * dstart Original content starting coordinate, generally 0 * dend Original content end point coordinate, generally dest length-1 */ @Override public CharSequence filter(CharSequence src, int start, int end, Spanned dest, int dstart, int dend) { String oldtext = dest.toString(); System.out.println(oldtext); //Verify delete etc if ("".equals(src.toString())) { return null; } //Verify non numeric or decimal points Matcher m = p.matcher(src); if(oldtext.contains(".")){ //Only numbers can be entered when a decimal point already exists if(!m.matches()){ return null; } }else{ //If no decimal point is entered, you can enter decimal point and number if(!m.matches() && !src.equals(".") ){ return null; } } //Verify the size of the input amount if(!src.toString().equals("")){ double dold = Double.parseDouble(oldtext+src.toString()); if(dold > MAX_VALUE){ CustomerToast.showToast(RechargeActivity.this, "The maximum amount entered cannot be greater than MAX_VALUE"); return dest.subSequence(dstart, dend); }else if(dold == MAX_VALUE){ if(src.toString().equals(".")){ CustomerToast.showToast(RechargeActivity.this, "The maximum amount entered cannot be greater than MAX_VALUE"); return dest.subSequence(dstart, dend); } } } //Verify decimal accuracy is correct if(oldtext.contains(".")){ int index = oldtext.indexOf("."); int len = dend - index; //Decimal places can only be 2 if(len > PONTINT_LENGTH){ CharSequence newText = dest.subSequence(dstart, dend); return newText; } } return dest.subSequence(dstart, dend) +src.toString(); } }
Call:
InputFilter[] filters = { new EditInputFilter() }; edit.setFilters(filters);
3. Limit input range method 3 (one method I use):
/** * Set decimal control */ private InputFilter lendFilter = new InputFilter() { public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) { // Delete special characters and return directly if ("".equals(source.toString())) { return null; } String dValue = dest.toString(); String[] splitArray = dValue.split("\\."); if (splitArray.length > 1) { String dotValue = splitArray[1]; int diff = dotValue.length() + 1 - 4;//2 represents the number of decimal places in the input box if (diff > 0) { return source.subSequence(start, end - diff); } } return null; } };
Call:
et_lend_maximum_number.setFilters(new InputFilter[]{lendFilter});
4. Control by layout attribute:
maxLength, inputType, minLength, digits, etc
a. Set the android:digits property of EditText to indicate the characters to be supported. For example, to restrict the input of numbers and letters, you can:
android:digits="0123456789abcdefghijklmnopqrstuvwxyz". PS: Tucao, which is very tired, does not support interval operators ~ or -
b. By the way, the inputType property:
<EditText //Phone number android:inputType="phone" //Text type, mostly uppercase, lowercase and numeric symbols. android:inputType="none" android:inputType="text" android:inputType="textCapCharacters" //Alphabetic capitalization android:inputType="textCapWords" //title case android:inputType="textCapSentences" //Capitalize first letter only android:inputType="textAutoCorrect" //Auto completion android:inputType="textAutoComplete" //Auto completion android:inputType="textMultiLine" //Multiline input android:inputType="textImeMultiLine" //IME multiline (if supported) android:inputType="textNoSuggestions" //No prompt android:inputType="textUri" //Website android:inputType="textEmailAddress" //e-mail address android:inputType="textEmailSubject" //Mail theme android:inputType="textShortMessage" //SMS android:inputType="textLongMessage" //Long message android:inputType="textPersonName" //Name android:inputType="textPostalAddress" //address android:inputType="textPassword" //Password android:inputType="textVisiblePassword" //Visible passwords android:inputType="textWebEditText" //Text as a web form android:inputType="textFilter" //Text filtering android:inputType="textPhonetic" //Pinyin input //value type android:inputType="number" //number android:inputType="numberSigned" //Signed number format android:inputType="numberDecimal" //Floating point format with decimal point android:inputType="datetime" //Time and date android:inputType="date" //Date keyboard android:inputType="time" //Time keyboard />
c.imeOptions property
When we use Android's own soft keyboard to input text for EditText when our mobile phone is on the horizontal screen, if we don't make special settings, the soft keyboard will occupy the whole interface, so how to make the keyboard occupy only a part of the screen? In fact, you only need to change a small attribute!
<EditText android:id="@+id/text1" android:imeOptions="flagNoExtractUi"/>
In addition, android:imeOptinos can be used to set some interface settings for Android's own soft keyboard:
android:imeOptions="flagNoExtractUi" //Make the soft keyboard not full screen display, only occupy a part of the screen //At the same time, this property can also control the display content of the key in the lower right corner of the soft keyboard. By default, it is the Enter key android:imeOptions="actionNone" //No prompt to the right of the input box android:imeOptions="actionGo" //The key content in the lower right corner is start android:imeOptions="actionSearch" //Press the key in the lower right corner to search for the magnifier picture android:imeOptions="actionSend" //The key content in the lower right corner is send android:imeOptions="actionNext" //The key content in the lower right corner is "next" android:imeOptions="actionDone" //The key content in the lower right corner is "complete"
At the same time, it is possible for EditText to add a corresponding listener to capture the listening event when the user clicks the button in the lower right corner of the soft keyboard for processing.
editText.setOnEditorActionListener(new OnEditorActionListener() { @Override public boolean onEditorAction(TextView v, int actionId, KeyEvent event) { Toast.makeText(MainActivity.this, "text2", Toast.LENGTH_SHORT).show(); return false; } });