Android仿滴滴出行验证码输入框效果

1、前言

最近撸码忙成狗啊,果然从无到有的独立开发不是一般的累啊。。。。
最近公司项目中有一个类似滴滴出行填写验证码的弹框,下面是我撸出来的效果:

输入验证码.gif

中间的那个输入密码的6个框框其实就是用shape画的背景,通过监听EditText获取焦点来改变背景,废话少说,直接上代码吧。

2、效果实现

代码内容比较简单,所以大家可以直接看代码

VerificationCodeInput.java

  /**
   * @author hydCoder
   * @date 2017/9/22 14:39
   * @desc 输入验证码的自定义view
   * @email hyd_coder@163.com
   */

public class VerificationCodeInput extends LinearLayout implements TextWatcher, View.OnKeyListener{

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           = 4;
private              int      boxWidth      = 80;
private              int      boxHeight     = 80;
private              int      childHPadding = 14;
private              int      childVPadding = 14;
private              String   inputType     = TYPE_NUMBER;
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);
    inputType = a.getString(R.styleable.vericationCodeInput_inputType);
    boxWidth = (int) a.getDimension(R.styleable.vericationCodeInput_child_width, boxWidth);
    boxHeight = (int) a.getDimension(R.styleable.vericationCodeInput_child_height, boxHeight);
    initViews();

}


@Override
protected void onAttachedToWindow() {
    super.onAttachedToWindow();

}

@Override
protected void onDetachedFromWindow() {
    super.onDetachedFromWindow();


}

private void initViews() {
    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.setTransformationMethod(PasswordTransformationMethod.getInstance());
        } 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.setEms(1);
        editText.addTextChangedListener(this);
        addView(editText,i);
        mEditTextList.add(editText);

    }


}

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(false);
        }

    }
}

@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 + childHPadding;
        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) {
    } else {
        focus();
        checkAndCommit();
    }
}

@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).requestFocus();
            setBg(mEditTextList.get(currentPosition),true);
            setBg(mEditTextList.get(currentPosition+1),false);
            mEditTextList.get(currentPosition).setText("");
        }
    }
    return false;
}

public interface Listener {
    void onComplete(String content);
}

}
···
styles.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>

输入框获取焦点时的背景
verification_edit_bg_focus.xml

<shape xmlns:android="http://schemas.android.com/apk/res/android">
<solid android:color="#FFFFFF" />
<corners android:radius="8dip" />
<stroke
    android:width="2dip"
    android:color="@color/auxiliary_color" />
</shape>

输入框没有获取焦点时的背景
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/white" />
    <corners android:radius="8dip" />
    <stroke
        android:width="1dip"
        android:color="@color/divide_color"/>
</shape>

在界面中使用

<com.sdalolo.genius.ui.view.VerificationCodeInput
    android:digits="1234567890"
    android:id="@+id/verificationCodeInput"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_marginTop="25dp"
    android:layout_gravity="center_horizontal"
    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="5dp"
    android:layout_centerInParent="true"
    android:layout_marginBottom="16dp"/>

然后对它设置输入完成后的监听

verificationCodeInput.setOnCompleteListener(new VerificationCodeInput.Listener() {
        @Override
        public void onComplete(String content) {
            btn_confirm.setEnabled(true);
            btn_confirm.setBackgroundResource(R.drawable.btn_bg_shape_enable);
            btn_confirm.setTextColor(Color.parseColor("#e4c16a"));
            codeNum = content;
        }
    });

到这里就可以完成和滴滴出行类似的效果了,是不是很简单,如果你刚好有需要,直接拷过去用吧!

谢谢
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 217,542评论 6 504
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 92,822评论 3 394
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 163,912评论 0 354
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,449评论 1 293
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,500评论 6 392
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,370评论 1 302
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,193评论 3 418
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 39,074评论 0 276
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,505评论 1 314
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,722评论 3 335
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,841评论 1 348
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,569评论 5 345
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,168评论 3 328
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,783评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,918评论 1 269
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 47,962评论 2 370
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,781评论 2 354

推荐阅读更多精彩内容

  • Android 自定义View的各种姿势1 Activity的显示之ViewRootImpl详解 Activity...
    passiontim阅读 172,116评论 25 707
  • ¥开启¥ 【iAPP实现进入界面执行逐一显】 〖2017-08-25 15:22:14〗 《//首先开一个线程,因...
    小菜c阅读 6,409评论 0 17
  • 《裕语言》速成开发手册3.0 官方用户交流:iApp开发交流(1) 239547050iApp开发交流(2) 10...
    叶染柒丶阅读 26,744评论 5 19
  • 发现 关注 消息 iOS 第三方库、插件、知名博客总结 作者大灰狼的小绵羊哥哥关注 2017.06.26 09:4...
    肇东周阅读 12,103评论 4 62
  • 人生想要早点得分吗?想像打球的人,若只练瞄准,却老是球不出手,人不上场,恐怕会沦为白练。球场上状况百出,身历其境,...
    蜗牛吃韭菜阅读 270评论 0 0