先上效果图让大家看看

1.VerficationCodeInput.Java

/**
 * 輸入验证码的自定义view
 *
 */
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 = 60;
    private int boxHeight = 60;
    private int childHPadding = 14;
    private int childVPadding = 14;
    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);
        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);
            }}Log.d(TAG, "checkAndCommit:" + stringBuilder.toString());
        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);
        Log.d(getClass().getName(), "onMeasure");
        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) {Log.d(getClass().getName(), "onLayout");
        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);
    }}

2.attrs.XML

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <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>

</resources>

3.输入框输入文字和没输入文字不同的状态

verification_edit_bg_focus.xml

<?xml version="1.0" encoding="utf-8"?>

<shape xmlns:android="http://schemas.android.com/apk/res/android">
    <solid android:color="#FFFFFF" />
    <corners android:radius="2dip" />
    <stroke
        android:width="3dip"
        android:color="#ffee33" />
</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="#FaFafa" />
    <corners android:radius="2dip" />
    <stroke
        android:width="1dip"
        android:color="#BDC7D8" />
</shape>

4.在Activity中使用

public class YanZhenMaActivity extends Activity {@Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {super.onCreate(savedInstanceState);
        setContentView(R.layout.yanzhen_activity);

    }
}

布局文件

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="输入验证码:"
    android:padding="12dp"
    />
<com.nuoyuan.njs.VerificationCodeInput
    android:digits="1234567890."
    android:id="@+id/verificationCodeInput"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    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"
    />

好了,到这里,自定义验证码输入框完成。。。。。。。。。。。。。。。。。。。。。。

Android自定义View实现滴滴验证码输入框效果相关推荐

  1. Android 自定义View之随机数验证码(仿写鸿洋)

    前言 本文面向自定义view新手,但是希望你最好有一定的理论知识,或基础概念,有的地方可能会一笔带过并不会细讲,细讲篇幅就太长了. 本文仿写自鸿洋的自定义View (一),尽管过去了将近快7年之久,我 ...

  2. Android自定义View,跟随手指滑动效果

    Android自定义View,实现跟随手指滑动效果, 效果如下: 一,重写onTouchEvent方法 最后返回true 二,在MotionEvent.ACTION_MOVE情况下改变自定义view ...

  3. android自定义拱形,Android自定义View实现圆弧进度的效果

    前言 Android开发中,常常自定义View实现自己想要的效果,当然自定义View也是Android开发中比较难的部分,涉及到的知识有Canvas(画布),Paint(画笔)等,自定义控件分为三种: ...

  4. android自定义计步器形状,Android自定义View仿QQ运动步数效果

    本文实例为大家分享了Android QQ运动步数的具体代码,供大家参考,具体内容如下 今天我们实现下面这样的效果: 首先自定义属性: 自定义View代码如下: /** * Created by Mic ...

  5. android 图片跑马灯动画,【Android自定义View】- 文本跑马灯效果

    简介 有些时候,文字过长,或者有多条需要展示的文本时,我们需要将文本进行左右滚动,多条文本时,还得上下滚动以实现展示不同的文本内容.这时候就需要我们自定义view来实现文本跑马灯效果了. 效果图 jj ...

  6. android 随机验证码,Android自定义View实现随机验证码

    对于android开发来说自定义View还是一个比较重要的技能,所以在这里写一篇自定义View入门的文章,也是实现一个相对简单的随机产生验证码的功能: 自定义View主要也就分为几步 1.自定义Vie ...

  7. Android自定义View(广告栏上下滚动效果)

    需求中涉及到的广告栏变化千变万化,这里,我们综合取材,有了下面的这篇文章. 开始的时候,我们使用的是MarqueeView,继承的ViewFlipper,但是会有一些bug,比如刷新数据时的重叠阴影等 ...

  8. android 屏幕飘动,Android自定义View实现飘动的叶子效果(三)

    上一篇对自定义View及一些方法有所了解,下面做一个简单的叶子飘动的例子 主要技术点 1.添加背景图片canvas.drawBitmap() 2.Matrix动画类 3.Matrix添加到画布上 步骤 ...

  9. android 抛物线轨迹,Android自定义View——贝塞尔曲线实现抛物线效果

    效果展示 原理分析 抛物线效果最主要的难点和原理在于贝塞尔曲线动画的生成,我们通过图片主要讲解贝塞尔曲线动画,这里用到的是二级贝塞尔曲线 1.需要找到贝塞尔曲线的三个点,开启点.结束点.控制点 2.通 ...

最新文章

  1. 【ACM】杭电OJ 2005
  2. Python简单主机批量管理工具
  3. 搭建eclipse版的ssm+maven+tk.mybatis+redis及mybatis+spring多数据源配置集成的demo
  4. python爬虫自学笔记分析解密_python爬虫学习笔记——1 各种文本分析工具简介之汇总...
  5. payara 创建 集群_高可用性(HA),会话复制,多VM Payara群集
  6. UNIX(多线程):19---Future 类型详解
  7. 各种操作系统简介和功能分析
  8. 俞渝欲花费百万召开“抢章座谈会” ?当当网回应来了
  9. 孤独的个人在社会中生存应掌握的基本健康技能(个人分析)
  10. CodeForces 785C Anton and Fairy Tale 二分
  11. python笔记(一)获取当前目录路径和文件(抄录)
  12. windows客户端连接linux服务器上的postmaster
  13. 哈希库--uthash的详细讲解(附uthash相关头文件下载)
  14. linux centos 网易云音乐,Centos7.4安装网易云音乐教程
  15. 基于大数据的高校贴吧舆情数据分析系统
  16. JavaSE实现汽车租赁系统
  17. HTML+CSS+JavaScript实现旅游网站官网
  18. Unity UI Text组件添加contentsizefitter后获取RectTransform宽度
  19. 中国颅骨固定系统行业市场供需与战略研究报告
  20. 4、<VBA>学习用刘永富老师插件解析JSON格式数据

热门文章

  1. MySQL 和 PostgreSQL 对比
  2. Matlab cell矩阵处理
  3. pip错误:TypeError: parse() got an unexpected keyword argument 'transport_encoding'
  4. 【Python】list转str
  5. 【完结】林轩田机器学习技法终章
  6. Karush-Kuhn-Tucker (KKT条件)
  7. C++Primer::头文件设计基本原则 与 预处理器介绍
  8. 经典SQL语句大全 收藏
  9. opengl从入门到精通
  10. 23种设计模式C++源码与UML实现--建造者模式