使用mob獲取手機驗證碼

1.輸入框是個自定義view

VerificationCodeInput
package com.example.sj.laddernetwork.regist_modul;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.text.Editable;
import android.text.InputFilter;
import android.text.InputType;
import android.text.TextWatcher;
import android.text.method.PasswordTransformationMethod;
import android.util.AttributeSet;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.LinearLayout;


import com.example.sj.laddernetwork.R;

import java.util.ArrayList;
import java.util.List;

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());
            LayoutParams layoutParams = new 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.WHITE);
            editText.setLayoutParams(layoutParams);
            editText.setCursorVisible(false);
            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;
            }
        }
    }

    @SuppressLint("NewApi")
    private void setBg(EditText editText, boolean focus) {
        if (boxBgNormal != null && !focus) {
            editText.setBackground(boxBgNormal);
        } else if (boxBgFocus != null && focus) {
            editText.setBackground(boxBgFocus);
        }
    }

    @SuppressLint("NewApi")
    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 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) {
        } 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.報錯得資源

R.styleable.vericationCodeInput
   <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>

3.驗證碼activity

package com.example.sj.laddernetwork;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.example.sj.laddernetwork.regist_modul.VerificationCodeInput;
import com.mob.MobSDK;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.smssdk.EventHandler;
import cn.smssdk.SMSSDK;

public class YanCodeActivity extends AppCompatActivity {

    @BindView(R.id.btn_back)
    ImageView btnBack;
    @BindView(R.id.verificationCodeInput)
    VerificationCodeInput verificationCodeInput;
    @BindView(R.id.get_code)
    TextView getCode;
    private EventHandler eh;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_yan_code);
        ButterKnife.bind(this);

        MobSDK.init(this);
        eh = new EventHandler() {
            @Override
            public void afterEvent(int event, int result, Object data) {
                Message msg = new Message();
                msg.arg1 = event;
                msg.arg2 = result;
                msg.obj = data;
                msg.what = 1;
                mHandler.sendMessage(msg);
            }

        };
        SMSSDK.registerEventHandler(eh);
    }

    @OnClick({R.id.btn_back, R.id.verificationCodeInput, R.id.get_code})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.btn_back:
                YanCodeActivity.this.finish();
                break;
            case R.id.verificationCodeInput:
                break;
            case R.id.get_code:
                //註冊回調監聽,放到發送和驗證前註冊,注意這裏是子線程需要傳到主線程中去操作後續提示


                // 請求驗證碼,其中country表示國家代碼,如“86”;phone表示手機號碼,如“13800138000”
                SMSSDK.getVerificationCode("86", RegistActivity.number);

                // 提交驗證碼,其中的code表示驗證碼,如“1357”
                //獲取自定義輸入框得監聽
                verificationCodeInput.setOnCompleteListener(new VerificationCodeInput.Listener() {
                    @Override
                    public void onComplete(String content) {
                        SMSSDK.submitVerificationCode(content, RegistActivity.number, "86");

                    }
                });

                break;
        }
    }

//EventHandler將信息給mHandler 
    @SuppressLint("HandlerLeak")
    Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
          //  Toast.makeText(YanCodeActivity.this, "驗證成功...", Toast.LENGTH_SHORT).show();
            switch (msg.what) {
                case 1:
                    Object o = msg.obj;
                    int a = msg.arg1;
                    int b = msg.arg2;
                    if (a == SMSSDK.EVENT_SUBMIT_VERIFICATION_CODE) {
                        Toast.makeText(YanCodeActivity.this, "驗證成功...3秒後跳到主界面", Toast.LENGTH_SHORT).show();
                        try {
                            Thread.sleep(3000);
                            startActivity(new Intent(YanCodeActivity.this,ShouActivity.class));
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
            }
        }
    };

    protected void onStop() {
        super.onStop();
        //用完回調要註銷掉,否則可能會出現內存泄露
        SMSSDK.unregisterEventHandler(eh);
    }
}

4.activity得xml佈局

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@mipmap/img_bb"
    android:orientation="vertical"
    tools:context=".YanCodeActivity"
    xmlns:var="http://schemas.android.com/apk/res-auto"
    >

    <ImageView
        android:id="@+id/btn_back"
        android:layout_width="30dp"
        android:layout_height="30dp"
        android:src="@mipmap/btn_back" />

    <TextView
        style="@style/text"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:layout_marginTop="97dp"
        android:text="驗證手機號"
        android:textSize="30sp" />

    <TextView
        style="@style/text"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:layout_marginTop="20dp"
        android:text="+86"
        android:textColor="@color/alpha_50_white"
        android:textSize="20sp" />

    <android.support.v4.widget.Space
        android:layout_width="match_parent"
        android:layout_height="50dp" />

    <com.example.sj.laddernetwork.regist_modul.VerificationCodeInput
        android:id="@+id/verificationCodeInput"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:layout_marginBottom="16dp"
        var:box="4"
        var:box_bg_focus="@drawable/white_line_reac"
        var:box_bg_normal="@drawable/white_line_reac"
        var:child_h_padding="12dp"
        var:child_height="63dp"
        var:child_width="42dp"
        android:gravity="center"
     ></com.example.sj.laddernetwork.regist_modul.VerificationCodeInput>
    <TextView
        android:id="@+id/get_code"
        android:layout_marginTop="40dp"
        android:textColor="@color/alpha_50_white"
        android:gravity="center"
        android:text="點擊獲取驗證碼"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />
</LinearLayout>

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章