Android EditText input Detection

Source: Internet
Author: User

Android EditText input Detection

A Story occurred when a function was recently developed. The plot is as follows:

The function is not complex, and an EditText is needed to obtain the user input information. Therefore, I made a Dialog to display my input interface (the Code is as follows ):

 

mAlertDialog = new AlertDialog.Builder(this)//, android.R.style.Theme_Holo_Light                .setIcon(R.drawable.ic_dialog_info_light)                .setTitle(R.string.model_rename_device)                .setView(createDialogView(deviceName))                .setPositiveButton(android.R.string.ok,                        new DialogInterface.OnClickListener() {                            public void onClick(DialogInterface dialog, int which) {                                //String deviceName = mDeviceNameView.getText().toString();                                reset_success=false;                                reset_model_name(mDeviceNameView.getText().toString());//finish();                            }                        })                .setNegativeButton(android.R.string.cancel,                new DialogInterface.OnClickListener() {                            public void onClick(DialogInterface dialog, int which) {//finish();                            }                        }).setOnDismissListener(new DialogInterface.OnDismissListener() {@Overridepublic void onDismiss(DialogInterface arg0) {if(reset_success){start_confir_ResetPhone();}else{finish();}}})                .create();mAlertDialog.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);        mAlertDialog.show();

    private View createDialogView(String deviceName) {        final LayoutInflater layoutInflater = (LayoutInflater)this            .getSystemService(Context.LAYOUT_INFLATER_SERVICE);        View view = layoutInflater.inflate(R.layout.dialog_edittext, null);        mDeviceNameView = (EditText) view.findViewById(R.id.edittext);        mDeviceNameView.setFilters(new InputFilter[] {                new Utf8ByteLengthFilter(MODEL_NAME_MAX_LENGTH_BYTES)        });        mDeviceNameView.setText(deviceName);    // set initial value before adding listener        mDeviceNameView.addTextChangedListener(this);        mDeviceNameView.setOnEditorActionListener(new TextView.OnEditorActionListener() {            @Override            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {                if (actionId == EditorInfo.IME_ACTION_DONE) {                    reset_model_name(v.getText().toString());                    mAlertDialog.dismiss();//finish();                    return true;    // action handled                } else {                //finish();                    return false;   // not handled                }            }        });mDeviceNameView.setSelection(mDeviceNameView.length());        return view;    }
Implementation is simple! However, when I store user input strings, the problem arises!

 

Originally, the string entered by this user needs to be stored in a self-configured nv section. What's important is that the space for the string to be stored is only 20 bytes, and the error is byte. therefore, it is very easy to enter a maximum of 20 characters. Because it is of the byte type, the input character must be checked. The character must be in a byte value (0-127) inside. it is actually an asic code.

Therefore, we need to check the input characters.

To detect EditText input characters in real time, You need EditText. addTextChangedListener () to add a TextWatcher detector and implement the following methods:

Public void afterTextChanged (Editable s)

Public void beforeTextChanged (CharSequence s, int start, int count, int after)

Public void onTextChanged (CharSequence s, int start, int before, int count)

The first way to think of it is to determine whether the current input character is correct in the afterTextChanged method. If not, change it through Editable s: s. delete () to delete. you can also directly use this EditText to re-set the input character: setText ();

In fact, neither of these methods works. Exceptions may occur when incorrect characters are entered quickly, which is obviously a synchronization problem.

Soon I came up with another solution: check whether there are any abnormal characters in onTextChanged (), and if so, send messages by Handler.

 

public void onTextChanged(CharSequence s, int start, int before, int count) {for(int i=0; i < count; i++){if(s.charAt(i+start) > 127 || s.charAt(i+start) < 0){Message msg = mHandler.obtainMessage(handleMessage_detection_MG);msg.obj = s;mHandler.sendMessage(msg);break;}}//Log.d(DEBUG_STR,"onTextChanged str="+s.toString()+"start="+start+"; before="+before+"; count="+count);}

    Handler mHandler = new Handler() {        public void handleMessage(Message msg) {switch (msg.what) {case handleMessage_detection_MG: InptText_Error_correction((CharSequence) msg.obj);break;case handleMessage_blue_name_MG: InptText_rename_blue((String) msg.obj);break;default:break;}}    };

 

 

private void InptText_Error_correction(CharSequence chars){if(chars != null){StringBuilder str_b = new StringBuilder(chars);char temp;int start_indx = -1;for(int i = 0; i < str_b.length(); i++){temp = str_b.charAt(i);if(temp > 127 || temp < 0){if(start_indx < 0){start_indx = i;}str_b.deleteCharAt(i);}}mDeviceNameView.setText(str_b.toString());if(start_indx < 0){start_indx = mDeviceNameView.length();}mDeviceNameView.setSelection(start_indx);Toast.makeText(Rename_model_activity.this, getString(R.string.set_name_Error_Character_notice),Toast.LENGTH_SHORT).show();}}


Finally, you can use EditText. setFilters () to configure the restrictions on input characters:

 

 

        mDeviceNameView.setFilters(new InputFilter[] {                new Utf8ByteLengthFilter(MODEL_NAME_MAX_LENGTH_BYTES)        });

MODEL_NAME_MAX_LENGTH_BYTES indicates the maximum length of the input character. Utf8ByteLengthFilter is a subclass of InputFilter. This is the adaptation to the input length. In fact, you will soon find out! InputFilter is a detector for input characters. therefore, it is not difficult to detect input Character Errors. In fact, InputFilter can completely solve this problem. implementation Method: public CharSequence filter (CharSequence source, int start, int end, Spanned dest, int dstart, int dend)
For the input error characters, you can return "" In Bytes:

 

For (int I = start; I <end; I ++ ){
Char c = source. charAt (I );

If (c> 127 | c <0 ){
Return "";
}

}

 

 

 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.