效果
场景
设置解锁密码 , 验证码输入
功能
输入框自动弹出 , 焦点始终在最起始未输入位置
代码
1.添加VerificationCodeInput.java
public class VerificationCodeInput extends LinearLayout implements TextWatcher, View.OnKeyListener, View.OnFocusChangeListener {
private final static String TYPE_NUMBER = "number";
private final static String TYPE_TEXT = "text";
private final static String TYPE_PASSWORD = "password";
private final static String TYPE_PHONE = "phone";
private static final String TAG = "VerificationCodeInput";
private int box = 6;
private int boxWidth = 40;
private int boxHeight = 40;
private int childHPadding = 16;
private int childVPadding = 16;
private String inputType = TYPE_PASSWORD;
private Drawable boxBgFocus = null;
private Drawable boxBgNormal = null;
private Listener listener;
private boolean focus = false;
private List<EditText> mEditTextList = new ArrayList<>();
private int currentPosition = 0;
public VerificationCodeInput(Context context, AttributeSet attrs) {
super(context, attrs);
TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.vericationCodeInput);
box = a.getInt(R.styleable.vericationCodeInput_box, 4);
childHPadding = (int) a.getDimension(R.styleable.vericationCodeInput_child_h_padding, 0);
childVPadding = (int) a.getDimension(R.styleable.vericationCodeInput_child_v_padding, 0);
boxBgFocus = a.getDrawable(R.styleable.vericationCodeInput_box_bg_focus);
boxBgNormal = a.getDrawable(R.styleable.vericationCodeInput_box_bg_normal);
if (DaoHelper.getInstance().getSkinMode().equals("white")) {
boxBgFocus = getResources().getDrawable(R.drawable.verification_edit_bg_focus_white);
boxBgNormal = getResources().getDrawable(R.drawable.verification_edit_bg_normal_white);
}
// inputType = a.getString(R.styleable.vericationCodeInput_inputType);
boxWidth = (int) a.getDimension(R.styleable.vericationCodeInput_child_width, boxWidth);
boxWidth = DensityUtil.dip2px(context, boxWidth);
boxHeight = (int) a.getDimension(R.styleable.vericationCodeInput_child_height, boxHeight);
boxHeight = DensityUtil.dip2px(context, boxHeight);
initViews();
}
@Override
protected void onAttachedToWindow() {
super.onAttachedToWindow();
}
@Override
protected void onDetachedFromWindow() {
super.onDetachedFromWindow();
}
private void initViews() {
setGravity(Gravity.CENTER);
for (int i = 0; i < box; i++) {
EditText editText = new EditText(getContext());
LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(boxWidth, boxHeight);
layoutParams.bottomMargin = childVPadding;
layoutParams.topMargin = childVPadding;
layoutParams.leftMargin = childHPadding;
layoutParams.rightMargin = childHPadding;
layoutParams.gravity = Gravity.CENTER;
editText.setOnKeyListener(this);
if (i == 0)
setBg(editText, true);
else setBg(editText, false);
editText.setTextColor(Color.BLACK);
editText.setLayoutParams(layoutParams);
editText.setGravity(Gravity.CENTER);
editText.setInputType(EditorInfo.TYPE_CLASS_PHONE);
editText.setFilters(new InputFilter[]{new InputFilter.LengthFilter(1)});
if (TYPE_NUMBER.equals(inputType)) {
editText.setInputType(InputType.TYPE_CLASS_NUMBER);
} else if (TYPE_PASSWORD.equals(inputType)) {
editText.setInputType(InputType.TYPE_CLASS_NUMBER);
editText.setTransformationMethod(new AsteriskPasswordTransformationMethod());
} else if (TYPE_TEXT.equals(inputType)) {
editText.setInputType(InputType.TYPE_CLASS_TEXT);
} else if (TYPE_PHONE.equals(inputType)) {
editText.setInputType(InputType.TYPE_CLASS_PHONE);
}
editText.setId(i);
editText.setCursorVisible(true);
editText.setEms(1);
editText.setOnClickListener(v -> editText.setSelection(editText.getText().length()));
editText.addTextChangedListener(this);
editText.setOnFocusChangeListener(this);
editText.setLongClickable(false);
addView(editText, i);
mEditTextList.add(editText);
}
postDelayed(() -> {
mEditTextList.get(0).requestFocus();
InputMethodManager imm = (InputMethodManager) getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
imm.showSoftInput(mEditTextList.get(0), 0);
}, 500);
}
private void backFocus() {
int count = getChildCount();
EditText editText;
for (int i = count - 1; i >= 0; i--) {
editText = (EditText) getChildAt(i);
if (editText.getText().length() == 1) {
editText.requestFocus();
setBg(mEditTextList.get(i), true);
//setBg(mEditTextList.get(i-1),true);
editText.setSelection(1);
return;
}
}
}
private void focus() {
int count = getChildCount();
EditText editText;
for (int i = 0; i < count; i++) {
editText = (EditText) getChildAt(i);
if (editText.getText().length() < 1) {
editText.requestFocus();
return;
}
}
}
private void setBg(EditText editText, boolean focus) {
if (boxBgNormal != null && !focus) {
editText.setBackground(boxBgNormal);
} else if (boxBgFocus != null && focus) {
editText.setBackground(boxBgFocus);
}
}
private void setBg() {
int count = getChildCount();
EditText editText;
for (int i = 0; i < count; i++) {
editText = (EditText) getChildAt(i);
if (boxBgNormal != null && !focus) {
editText.setBackground(boxBgNormal);
} else if (boxBgFocus != null && focus) {
editText.setBackground(boxBgFocus);
}
}
}
private void checkAndCommit() {
StringBuilder stringBuilder = new StringBuilder();
boolean full = true;
for (int i = 0; i < box; i++) {
EditText editText = (EditText) getChildAt(i);
String content = editText.getText().toString();
if (content.length() == 0) {
full = false;
break;
} else {
stringBuilder.append(content);
}
}
if (full) {
if (listener != null) {
listener.onComplete(stringBuilder.toString());
setEnabled(true);
}
}
}
@Override
public void setEnabled(boolean enabled) {
int childCount = getChildCount();
for (int i = 0; i < childCount; i++) {
View child = getChildAt(i);
child.setEnabled(enabled);
}
}
public void setOnCompleteListener(Listener listener) {
this.listener = listener;
}
@Override
public LayoutParams generateLayoutParams(AttributeSet attrs) {
return new LinearLayout.LayoutParams(getContext(), attrs);
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
int count = getChildCount();
for (int i = 0; i < count; i++) {
View child = getChildAt(i);
this.measureChild(child, widthMeasureSpec, heightMeasureSpec);
}
if (count > 0) {
View child = getChildAt(0);
int cHeight = child.getMeasuredHeight();
int cWidth = child.getMeasuredWidth();
int maxH = cHeight + 2 * childVPadding;
int maxW = (cWidth + childHPadding) * box;
setMeasuredDimension(resolveSize(maxW, widthMeasureSpec),
resolveSize(maxH, heightMeasureSpec));
}
}
@Override
protected void onLayout(boolean changed, int l, int t, int r, int b) {
int childCount = getChildCount();
for (int i = 0; i < childCount; i++) {
View child = getChildAt(i);
child.setVisibility(View.VISIBLE);
int cWidth = child.getMeasuredWidth();
int cHeight = child.getMeasuredHeight();
int cl = (i) * (cWidth + childHPadding);
int cr = cl + cWidth;
int ct = childVPadding;
int cb = ct + cHeight;
child.layout(cl, ct, cr, cb);
}
}
@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 && count >= 1 && currentPosition != mEditTextList.size() - 1) {
currentPosition++;
mEditTextList.get(currentPosition).requestFocus();
setBg(mEditTextList.get(currentPosition), true);
setBg(mEditTextList.get(currentPosition - 1), false);
}
}
@Override
public void afterTextChanged(Editable s) {
if (s.length() == 0) {
if (listener != null) {
listener.onInput();
}
} else {
focus();
checkAndCommit();
}
}
@Override
public void onFocusChange(View v, boolean hasFocus) {
boolean isRequest = false;
if (hasFocus) {
for (int i = 0; i < mEditTextList.size(); i++) {
EditText editText = mEditTextList.get(i);
if (editText.getText().length() < 1) {
isRequest = true;
editText.requestFocus();
InputMethodManager imm = (InputMethodManager) getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
imm.showSoftInput(editText, 0);
return;
}
}
if (!isRequest) {
EditText editText = mEditTextList.get(mEditTextList.size() - 1);
editText.requestFocus();
editText.setSelection(editText.getText().length());
}
}
}
@Override
public boolean onKey(View view, int keyCode, KeyEvent event) {
EditText editText = (EditText) view;
if (keyCode == KeyEvent.KEYCODE_DEL && editText.getText().length() == 0) {
int action = event.getAction();
if (currentPosition != 0 && action == KeyEvent.ACTION_DOWN) {
currentPosition--;
mEditTextList.get(currentPosition).setText("");
mEditTextList.get(currentPosition).requestFocus();
setBg(mEditTextList.get(currentPosition), true);
setBg(mEditTextList.get(currentPosition + 1), false);
}
}
return false;
}
public interface Listener {
void onComplete(String content);
void onInput();
}
}
2.添加AsteriskPasswordTransformationMethod.java
public class AsteriskPasswordTransformationMethod extends PasswordTransformationMethod {
@Override
public CharSequence getTransformation(CharSequence source, View view) {
return new PasswordCharSequence(source);
}
private class PasswordCharSequence implements CharSequence {
private CharSequence mSource;
public PasswordCharSequence(CharSequence source) {
mSource = source; // Store char sequence
}
@Override
public char charAt(int index) {
return '●'; // This is the important part
}
@Override
public int length() {
return mSource.length(); // Return default
}
@Override
public CharSequence subSequence(int start, int end) {
return mSource.subSequence(start, end); // Return default
}
}
}
3.在attr.xml中设置
<declare-styleable name="vericationCodeInput">
<attr name="box" format="integer" />
<attr name="child_h_padding" format="dimension"/>
<attr name="child_v_padding" format="dimension"/>
<attr name="child_width" format="dimension"/>
<attr name="child_height" format="dimension"/>
<attr name="padding" format="dimension"/>
<attr name="box_bg_focus" format="reference"/>
<attr name="box_bg_normal" format="reference"/>
<attr name="inputType" format="string"/>
</declare-styleable>
4.未选中状态布局verification_edit_bg_normal.xml
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
<solid android:color="@color/comres_translute" />
<corners android:radius="8dip" />
<stroke
android:width="1px"
android:color="#b7aaf7"/>
</shape>
5.选中状态布局verification_edit_bg_focus.xml
<shape xmlns:android="http://schemas.android.com/apk/res/android">
<solid android:color="@color/comres_translute" />
<corners android:radius="8dip" />
<stroke
android:width="2px"
android:color="#c8bbf8" />
</shape>
6.布局中使用
<com.mvp.org.coustomview.VerificationCodeInput
android:digits="1234567890"
android:id="@+id/verificationCodeInput"
android:layout_width="wrap_content"
android:gravity="center"
android:layout_height="wrap_content"
android:layout_marginTop="118px"
android:layout_gravity="center"
ver:box="6"
ver:box_bg_normal="@drawable/verification_edit_bg_normal"
ver:box_bg_focus="@drawable/verification_edit_bg_focus"
ver:child_h_padding="16dp"
android:layout_marginLeft="8dp"
android:layout_marginBottom="16dp"/>
7.代码中应用
boolean isFinish = false;
String Password;
verificationCodeInput.setOnCompleteListener(new VerificationCodeInput.Listener() {
@Override
public void onComplete(String content) {
Password = content;
isFinish = true;
}
@Override
public void onInput() {
isFinish = false;
}
});