Android EditText 分割文字输入
jopen
9年前
先上效果:
不多说,代码如下:
package com.example.testedit; import android.content.Context; import android.graphics.Canvas; import android.text.Editable; import android.text.TextWatcher; import android.util.AttributeSet; import android.widget.EditText; public class DivisionEditText extends EditText { private char separate= ' '; private int groupLength = 4; public DivisionEditText(Context context) { super(context); setup(); } public DivisionEditText(Context context, AttributeSet attrs) { super(context, attrs); setup(); } public DivisionEditText(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); setup(); } private void setup(){ this.addTextChangedListener(new TextWatcher() { @Override public void onTextChanged(CharSequence s, int start, int before, int count) { System.out.println(s); Editable e = DivisionEditText.this.getEditableText(); int oldLength = e.toString().length(); int oldsection = oldLength/groupLength; boolean isNeedContinue = false; for(int i = 1; i <= oldsection; i++){ if((groupLength+1)*i - 1 < oldLength){ if(e.charAt((groupLength+1)*i - 1) != separate){ isNeedContinue = true; break; } } } if(isNeedContinue){ StringBuilder sb =new StringBuilder(); /*sb.append(e.toString()); for(int i = 0; i < sb.toString().length(); i++){ if(sb.charAt(i) == separate){ sb.delete(i, i+1); i--; } }*/ //换更简洁的代码 String temp = e.toString().replaceAll(String.valueOf(separate), ""); sb.append(temp); int newLength = sb.length(); int section = newLength/groupLength; System.out.println(section + " " + sb.toString()); for(int i = 1; i <= section; i++){ if((groupLength+1)*i - 1 < sb.length()){ sb.insert((groupLength+1)*i - 1, separate); } } System.out.println("sb - "+sb.toString()); e.replace(0, e.toString().length(), sb); System.out.println(e.toString()); } } @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { } @Override public void afterTextChanged(Editable s) { } }); } @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); } public char getSeparate() { return separate; } public void setSeparate(char separate) { this.separate = separate; } public int getGroupLength() { return groupLength; } public void setGroupLength(int groupLength) { this.groupLength = groupLength; } }