Android 支付密碼框控件簡單實現

簡單的實現支付密碼框,可以控制密碼個數,背景

效果圖奉上

效果圖

1.控件主要有7個參數
bgdrawable 背景 (建議透明)
pwdlength 密碼長度
splilinewidth 分割線寬度
splilinecolor 分割線顏色
pwdcolor 密碼字體顏色
pwdsize 密碼字體大小
bgdrawable 第一個為默認背景 第二個為填充背景 (選填,但要填滿2個)

import android.content.Context;
import android.text.Editable;
import android.text.InputFilter;
import android.text.InputType;
import android.text.Selection;
import android.text.TextWatcher;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.PasswordTransformationMethod;
import android.util.AttributeSet;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;


/**
 * 支付密碼
 * Created by yyx on 2016/7/10.
 */
public class PayPwdEditText extends RelativeLayout {

    private EditText editText; //文本編輯框
    private Context context;

    private LinearLayout linearLayout; //文本密碼的文本
    private TextView[] textViews; //文本數組

    private int pwdlength = 6; //密碼長度, 默認6
    private int[] bgdrawables; //背景圖片

    private OnTextFinishListener onTextFinishListener;


    public PayPwdEditText(Context context) {
        this(context, null);
    }

    public PayPwdEditText(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public PayPwdEditText(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        this.context = context;
    }

    /**
     * @param bgcolor    背景顏色
     * @param pwdlength     密碼長度
     * @param splilinewidth 分割線寬度
     * @param splilinecolor 分割線顏色
     * @param pwdcolor      密碼字體顏色
     * @param pwdsize       密碼字體大小
     * @param bgdrawable    第一個為默認背景 第二個為填充背景  (選填,但要填滿2個)
      */
    public void initStyle(int bgcolor, int pwdlength, float splilinewidth, int splilinecolor, int pwdcolor, int pwdsize, int... bgdrawable) {
        this.pwdlength = pwdlength;
        initEdit(bgcolor);
        bgdrawables = new int[]{};
        if (bgdrawable.length > 1){
            bgdrawables = new int[]{bgdrawable[0],bgdrawable[1]};
        }
        initShowInput(bgcolor, pwdlength, splilinewidth, splilinecolor, pwdcolor, pwdsize);
    }

    /**
     * 初始化編輯框
     *
     * @param bgcolor
     */
    private void initEdit(int bgcolor) {
        editText = new EditText(context);
        editText.setBackgroundResource(bgcolor);
        editText.setCursorVisible(false);
        editText.setTextSize(0);
        editText.setInputType(InputType.TYPE_NUMBER_VARIATION_PASSWORD | InputType.TYPE_CLASS_NUMBER);
        editText.setFilters(new InputFilter[]{new InputFilter.LengthFilter(pwdlength)});
        editText.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
                Editable etext = editText.getText();
                Selection.setSelection(etext, etext.length());
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                initDatas(s);
                if (s.length() == pwdlength) {
                    if (onTextFinishListener != null) {
                        onTextFinishListener.onFinish(s.toString().trim());
                    }
                }
            }
        });
        LayoutParams lp = new LayoutParams(LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
        lp.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM, RelativeLayout.TRUE);
        addView(editText, lp);

    }

    /**
     * @param bgcolor       背景drawable
     * @param pwdlength     密碼長度
     * @param slpilinewidth 分割線寬度
     * @param splilinecolor 分割線顏色
     * @param pwdcolor      密碼字體顏色
     * @param pwdsize       密碼字體大小
     */
    public void initShowInput(int bgcolor, int pwdlength, float slpilinewidth, int splilinecolor, int pwdcolor, int pwdsize) {
        //添加密碼框父布局
        linearLayout = new LinearLayout(context);
        linearLayout.setBackgroundResource(bgcolor);
        LayoutParams layoutParams = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
        linearLayout.setLayoutParams(layoutParams);
        linearLayout.setOrientation(LinearLayout.HORIZONTAL);
        addView(linearLayout);

        //添加密碼框
        textViews = new TextView[pwdlength];
        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(0, LayoutParams.MATCH_PARENT);
        params.weight = 1;
        params.gravity = Gravity.CENTER;

        LinearLayout.LayoutParams params2 = new LinearLayout.LayoutParams(dip2px(context, slpilinewidth), LayoutParams.MATCH_PARENT);
        for (int i = 0; i < textViews.length; i++) {
            final int index = i;
            TextView textView = new TextView(context);
            textView.setGravity(Gravity.CENTER);
            textViews[i] = textView;
            if (bgdrawables.length > 1 && bgdrawables != null){
                textViews[i].setBackgroundResource(bgdrawables[0]);
            }
            textViews[i].setTextSize(pwdsize);
            textViews[i].setTextColor(context.getResources().getColor(pwdcolor));
            textViews[i].setInputType(InputType.TYPE_NUMBER_VARIATION_PASSWORD | InputType.TYPE_CLASS_NUMBER);
            linearLayout.addView(textView, params);


            if (i < textViews.length - 1) {
                View view = new View(context);
                view.setBackgroundColor(context.getResources().getColor(splilinecolor));
                linearLayout.addView(view, params2);
            }
        }
    }

    /**
     * 是否顯示明文
     *
     * @param showPwd
     */
    public void setShowPwd(boolean showPwd) {
        int length = textViews.length;
        for (int i = 0; i < length; i++) {
            if (showPwd) {
                textViews[i].setTransformationMethod(PasswordTransformationMethod.getInstance());
            } else {
                textViews[i].setTransformationMethod(HideReturnsTransformationMethod.getInstance());
            }
        }
    }

    /**
     * 設置顯示類型
     *
     * @param type
     */
    public void setInputType(int type) {
        int length = textViews.length;
        for (int i = 0; i < length; i++) {
            textViews[i].setInputType(type);
        }
    }

    /**
     * 清除文本框
     */
    public void clearText() {
        editText.setText("");
        for (int i = 0; i < pwdlength; i++) {
            textViews[i].setText("");
        }
    }

    public void setOnTextFinishListener(OnTextFinishListener onTextFinishListener) {
        this.onTextFinishListener = onTextFinishListener;
    }

    /**
     * 根據輸入字符,顯示密碼個數
     *
     * @param s
     */
    public void initDatas(Editable s) {
        if (s.length() > 0) {
            int length = s.length();
            for (int i = 0; i < pwdlength; i++) {
                if (i < length) {
                    for (int j = 0; j < length; j++) {
                        char ch = s.charAt(j);
                        textViews[j].setText(String.valueOf(ch));
                        if (bgdrawables.length > 1 && bgdrawables != null){
                            textViews[j].setBackgroundResource(bgdrawables[1]);
                        }
                    }
                } else {
                    textViews[i].setText("");
                    if (bgdrawables.length > 1 && bgdrawables != null){
                        textViews[i].setBackgroundResource(bgdrawables[0]);
                    }
                }
            }
        } else {
            for (int i = 0; i < pwdlength; i++) {
                textViews[i].setText("");
                if (bgdrawables.length > 1 && bgdrawables != null){
                    textViews[i].setBackgroundResource(bgdrawables[0]);
                }
            }
        }
    }

    /**
     *  密碼
     * @return
     */
    public String getPwdText() {
        if (editText != null)
            return editText.getText().toString().trim();
        return "";
    }

    public static int dip2px(Context context, float dipValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dipValue * scale + 0.5f);
    }

    public interface OnTextFinishListener {
        void onFinish(String str);
    }

}

2.xml 簡潔明了 寬高自定

<com.yyx.myapplication.widget.PayPwdEditText
        android:id="@+id/et_pay"
        android:layout_width="200dp"
        android:layout_height="40dp"
         />

3.1 實現不帶背景 xml 給個背景

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    
    <item>
        <shape>
            <corners android:radius="1px" />

            <stroke android:width="2px" android:color="@color/light_gray" />

            <solid android:color="@color/transparent" />
        </shape>
    </item>

</selector>

    <color name="transparent">#00000000</color>
    <color name="light_gray">#dddddd</color>
    <color name="black">#000000</color>

代碼實現 參數已在上面給出

PayPwdEditText et_pay = (PayPwdEditText) findViewById(R.id.et_pay);
et_pay.initStyle(R.color.transparent, 6, 1, R.color.light_gray, R.color.black, 20);

效果圖如下

不加背景

3.2 加入背景圖
去掉xml控件的背景 如果不嫌難看 - -
代碼實現相差不大,只是加多2個背景 加寬分割線且透明

et_pay.initStyle(R.color.transparent, 6, 5, R.color.transparent, R.color.black, 20, R.drawable.et_pay_bg, R.drawable.et_pay_bg2);

效果圖如下

加背景

4.打印輸出
調用

public String getPwdText() {
        if (editText != null)
            return editText.getText().toString().trim();
        return "";
    }
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容

  • Android 自定義View的各種姿勢1 Activity的顯示之ViewRootImpl詳解 Activity...
    passiontim閱讀 173,104評論 25 708
  • 發現 關注 消息 iOS 第三方庫、插件、知名博客總結 作者大灰狼的小綿羊哥哥關注 2017.06.26 09:4...
    肇東周閱讀 12,200評論 4 61
  • 最愁的, 是那莫名其妙, 迸發出孤獨的情緒, 同誰傾訴? 毫無征兆的, 說不了。
    老孩閱讀 244評論 0 1
  • 突然感覺好孤獨
    文鵬_35f7閱讀 156評論 0 0