自定义控件之 PasswordEditText(密码输入框)

Android自定义密码输入框——(仿支付宝等) Android自定义密码输入框,通过自定义输入显示框和自定义输入键盘,实现支付宝等 密码输入的效果,使用者可自定义密码是否可见。代码已托管到github,有需要的话可以 去我的github下载。 话不多说,先看效果: 图左为隐藏密码的显示效果,图右为不隐藏密码的显示效果,该可见性可由自定义密码输入框控件的isHide属性来确定   isHide="true" 表示隐藏输入的密码, 阅读详情

前两天在掘金上看到了一个验证码输入框,然后自己实现了一下,以前都是继承的 View,这次继承了 ViewGroup,也算是尝试了一点不同的东西。先看看最终效果:

事实上就是用将输入的密码用几个文本框来显示而已,要打造这样一个东西我刚开始也是一头雾水,不急,直接写不会,我们可以采取曲线救国的方法。下面我来说说我的思路。

1 准备工作

光看图上效果没有什么头绪的话,但是我相信下面这个布局大家肯定都会写:

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout 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"
    tools:context="com.qinshou.passwordedittext.MainActivity">

    <RelativeLayout
        android:layout_width="0dp"
        android:layout_height="80dp"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:orientation="horizontal">

            <TextView
                android:layout_width="0dp"
                android:layout_height="match_parent"
                android:layout_margin="10dp"
                android:layout_weight="1"
                android:background="@drawable/bg_inputing" />

            <TextView
                android:layout_width="0dp"
                android:layout_height="match_parent"
                android:layout_margin="10dp"
                android:layout_weight="1"
                android:background="@drawable/bg_inputed" />

            <TextView
                android:layout_width="0dp"
                android:layout_height="match_parent"
                android:layout_margin="10dp"
                android:layout_weight="1"
                android:background="@drawable/bg_inputed" />

            <TextView
                android:layout_width="0dp"
                android:layout_height="match_parent"
                android:layout_margin="10dp"
                android:layout_weight="1"
                android:background="@drawable/bg_inputed" />
        </LinearLayout>

        <EditText
            android:id="@+id/et_password"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:background="@null"
            android:cursorVisible="false" />
    </RelativeLayout>
</android.support.constraint.ConstraintLayout>

 

这样布局写出来的效果是这样:

 

这就是我们要的效果吧,所以下面的工作就简单了,就是把这个布局给封装到一个自定义控件中去。这里面有好多 View,所以我们需要继承的是一个 ViewGroup,根据上面的布局,选择继承 RelativeLayout。

 

2 写PasswordEditText布局

我们需要在一个 RelativeLayout 中添加 1 个横向的 LinearLayout 用来装 4 个 用来显示的 EditText,为什么用 EditText 不用 TextView 是因为 EditText 可以密文显示。然后还需要一个 EditText 来弹出软键盘用来输入。

 

public class PasswordEditText extends RelativeLayout {
    private Context mContext;
    private EditText mEditText;
    private List<EditText> editTexts;   //选用 EditText 而不用 TextView 是因为 EditText 可以密文显示

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

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

    public PasswordEditText(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        mContext = context;
        initView();
    }


    /**
     * Description:添加控件,密码框和不可见的输入框
     * Date:2017/8/18
     */
    private void initView() {
        //新建一个容器
        LinearLayout mLinearLayout = new LinearLayout(mContext);
        LinearLayout.LayoutParams linearLayoutParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT);
        mLinearLayout.setLayoutParams(linearLayoutParams);
        mLinearLayout.setOrientation(LinearLayout.HORIZONTAL);

        //根据 count 添加一定数量的密码框
        editTexts = new ArrayList<EditText>();
        LinearLayout.LayoutParams textViewParams = new LinearLayout.LayoutParams(getScreenWidth(mContext) / 4 - dip2px(mContext, 20), getScreenWidth(mContext) / count - dip2px(mContext, 20));
        textViewParams.setMargins(dip2px(mContext, 10), dip2px(mContext, 10), dip2px(mContext, 10), dip2px(mContext, 10));
        for (int i = 0; i < 4; i++) {
            EditText mEditText = new EditText(mContext);
            mEditText.setLayoutParams(textViewParams);
            mEditText.setBackgroundResource(R.drawable.bg_inputed); //设置背景
            mEditText.setGravity(Gravity.CENTER);   //设置文本显示位置
            mEditText.setTextSize(24);    //设置文本大小
            mEditText.setFocusable(false);  //设置无法获得焦点
            editTexts.add(mEditText);
            mLinearLayout.addView(mEditText);
        }
        editTexts.get(0).setBackgroundResource(R.drawable.bg_inputing);

        //添加不可见的 EditText
        LinearLayout.LayoutParams editTextParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT);
        mEditText = new EditText(mContext);
        mEditText.setLayoutParams(editTextParams);
        mEditText.setCursorVisible(false);  //设置输入游标不可见
        mEditText.setBackgroundResource(0); //设置透明背景,让下划线不可见
        mEditText.setAlpha(0.0f);   //设置为全透明,让输入的内容不可见
        mEditText.setInputType(InputType.TYPE_CLASS_NUMBER);    //设置只能输入数字
        mEditText.setFilters(new InputFilter[]{new InputFilter.LengthFilter(count)});   //限制输入长度

        addView(mLinearLayout);
        addView(mEditText);
    }

    /**
     * Description:获取屏幕宽度
     * Date:2017/8/18
     */
    private int getScreenWidth(Context context) {
        WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
        return wm.getDefaultDisplay().getWidth();
    }

    /**
     * 根据手机的分辨率从 dp 的单位 转成为 px(像素)
     */
    public static int dip2px(Context context, float dpValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dpValue * scale + 0.5f);
    }

    /**
     * 根据手机的分辨率从 px(像素) 的单位 转成为 dp
     */
    public static int px2dip(Context context, float pxValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (pxValue / scale + 0.5f);
    }

}


现在的效果就跟刚才一样了:

 

3 添加输入监听器

光有布局还不行,我们要让它可以输入,让输入的内容显示到对应的 4 个密码框中,这里监听的肯定是输入的那个 EditText,为其添加 TextWatcher,这里介绍一下 TextWatcher 这个监听器。

TextWatch 有 3 个回调方法:

public void beforeTextChanged(CharSequence s, int start, int count, int after):这是监听内容改变前,s 是内容改变前的文本,start 是内容改变操作后输入光标所在位置,count 删除内容时是删除字符的个数,增加内容时为 0,after 增加内容时是增加字符的个数,删除内容时为 0。
public void onTextChanged(CharSequence s, final int start, int before, int count):监听内容改变后,s 是内容改变后的文本,start 是内容改变操作后光标的位置,count 增加内容时是增加字符的个数,删除内容时为 0,after 删除内容时是删除字符的个数,增加内容时为 0。

public void afterTextChanged(Editable s):监听内容改变后,s 为内容改变后的文本。

 

我们主要的操作就是在 onTextChanged() 中,增加第一个密码,显示到第一个密码框中,增加第二个,显示到第二个上,删除时也是从后往前依次删除。

            mEditText.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            /**
             *
             * @param s 输入后的文本
             * @param start 输入的位置
             * @param before 输入的位置上之前的字符数
             * @param count 输入的位置上新输入的字符数
             */
            @Override
            public void onTextChanged(CharSequence s, final int start, int before, int count) {
                if (before == 0 && count == 1) {
                    //为对应显示框设置对应显示内容
                    editTexts.get(start).setText(s.subSequence(start, start + 1));
                    //修改输入了内容的密码框的背景
                    editTexts.get(start).setBackgroundResource(R.drawable.bg_inputed);
                    //如果还有下一个密码框,将其背景设置为待输入的背景
                    if (start + 1 < editTexts.size()) {
                        editTexts.get(start + 1).setBackgroundResource(R.drawable.bg_inputing);
                    } else {
                        //输入完成后关闭软键盘
                        InputMethodManager imm = (InputMethodManager) mContext.getSystemService(
                                Context.INPUT_METHOD_SERVICE);
                        imm.hideSoftInputFromWindow(mEditText.getWindowToken(), 0);
                    }
                } else if (before == 1 && count == 0) {
                    //清除退格位置对应显示框的内容
                    editTexts.get(start).setText("");
                    //将其退格的位置设置为明文显示
                    editTexts.get(start).setTransformationMethod(HideReturnsTransformationMethod.getInstance());
                    //设置退格位置的背景
                    for (EditText editText : editTexts) {
                        editText.setBackgroundResource(R.drawable.bg_inputed);
                    }
                    editTexts.get(start).setBackgroundResource(R.drawable.bg_inputing);
                }
            }

            @Override
            public void afterTextChanged(Editable s) {
            }
        });

 

现在效果已经初具成效了:


 

4 密文显示

然后我们需要在输入后一段时间变为密文显示,这里我选择了 0.5s,同时,在下一个密码框有输入时,如果上一个密码框还没有变为密文显示的话则立即将其设置为密文显示,这里同样是在 onTextChanged() 方法中操作:

            mEditText.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            /**
             *
             * @param s 输入后的文本
             * @param start 输入的位置
             * @param before 输入的位置上之前的字符数
             * @param count 输入的位置上新输入的字符数
             */
            @Override
            public void onTextChanged(CharSequence s, final int start, int before, int count) {
                if (before == 0 && count == 1) {
                    //为对应显示框设置对应显示内容
                    editTexts.get(start).setText(s.subSequence(start, start + 1));
                    //修改输入了内容的密码框的背景
                    editTexts.get(start).setBackgroundResource(R.drawable.bg_inputed);
                    //如果还有下一个密码框,将其背景设置为待输入的背景
                    if (start + 1 < editTexts.size()) {
                        editTexts.get(start + 1).setBackgroundResource(R.drawable.bg_inputing);
                    } else {
                        //输入完成后关闭软键盘
                        InputMethodManager imm = (InputMethodManager) mContext.getSystemService(
                                Context.INPUT_METHOD_SERVICE);
                        imm.hideSoftInputFromWindow(mEditText.getWindowToken(), 0);
                    }
                    //如果需要密文显示,则 0.5s 后设置为密文显示
                    editTexts.get(start).postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            editTexts.get(start).setTransformationMethod(PasswordTransformationMethod.getInstance());
                        }
                    }, 500);
                    //如果上一个显示框还不是密文显示的话,立即将其设置为密文显示,前提是需要密文显示
                    if (start > 0 && editTexts.get(start - 1).getTransformationMethod() instanceof HideReturnsTransformationMethod) {
                        editTexts.get(start - 1).setTransformationMethod(PasswordTransformationMethod.getInstance());
                    }
                } else if (before == 1 && count == 0) {
                    //清除退格位置对应显示框的内容
                    editTexts.get(start).setText("");
                    //将其退格的位置设置为明文显示
                    editTexts.get(start).setTransformationMethod(HideReturnsTransformationMethod.getInstance());
                    //设置退格位置的背景
                    for (EditText editText : editTexts) {
                        editText.setBackgroundResource(R.drawable.bg_inputed);
                    }
                    editTexts.get(start).setBackgroundResource(R.drawable.bg_inputing);
                }
            }

            @Override
            public void afterTextChanged(Editable s) {
            }
        });

 

效果如下:

 

5 添加自定义属性

至此,我已经实现了我想要的效果了,为了让它有更好的适应性,我们可以为其添加一些自定义属性,然后动态获取这些属性来更好的自定义这个控件,毕竟老去修改源码还是挺麻烦的:

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <declare-styleable name="PasswordEditText">
        <!-- 密码框数量 -->
        <attr name="count" format="integer" />
        <!-- 密码字体大小 -->
        <attr name="passwordSize" format="integer" />
        <!-- 是否显示输入的密码 -->
        <attr name="showPassword" format="boolean" />
        <!-- 下一个待输入的密码框的背景 -->
        <attr name="bgInputing" format="reference" />
        <!-- 已经输入了密码框的背景 -->
        <attr name="bgInputed" format="reference" />
    </declare-styleable>
</resources>

 

如何获取自定义属性这个网上很多教程,我也不赘述如何设置,具体的可以看看最后的完整源码。

 

6 总结

这是第一次写继承一个 ViewGroup,自定义控件这个东西,可以说是一直都得学,但永远也学不完,因为需求总是在变的,但是万变不离其宗,多写几个控件,我相信再复杂的控件,我们在加以思考后也能实现。最近找到了新工作,真的感觉自己很幸运,公司不错,同事也很好,希望自己能够快速融入其中然后帮着做事,实现自己的价值。新公司不算是很忙,但是感觉自己很多不会的,在闲暇时间我要继续提高自己,对得起自己的工作。

 

7 源码

package com.qinshou.passwordedittext;

import android.content.Context;
import android.content.res.TypedArray;
import android.text.Editable;
import android.text.InputFilter;
import android.text.InputType;
import android.text.TextWatcher;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.PasswordTransformationMethod;
import android.util.AttributeSet;
import android.util.Log;
import android.view.Gravity;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;

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

/**
 * Description:密码输入框,也可明文显示,用作输入验证码
 * Created by 禽兽先生
 * Created on 2017/8/17
 */

public class PasswordEditText extends RelativeLayout {
    private Context mContext;
    private EditText mEditText;
    private List<EditText> editTexts;   //选用 EditText 而不用 TextView 是因为 EditText 可以密文显示
    private int count = 4;  //密码框数量
    private int passwordSize = 24;  //密码文本大小
    private boolean showPassword = true;   //密码是否密文显示,true 为一直明文显示,false 为 0.5s 后密文显示
    private int bgInputing = R.drawable.bg_inputing; //待输入的密码框的背景
    private int bgInputed = R.drawable.bg_inputed;  //非待输入的密码框的背景
    private onCompletionListener mOnCompletionListener;

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

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

    public PasswordEditText(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        mContext = context;
        initAttr(attrs, defStyleAttr);
        initView();
        addListener();
    }

    /**
     * Description:初始化自定义属性
     * Date:2017/8/19
     */
    private void initAttr(AttributeSet attrs, int defStyleAttr) {
        TypedArray mTypeArray = mContext.getTheme().obtainStyledAttributes(attrs, R.styleable.PasswordEditText, defStyleAttr, 0);
        count = mTypeArray.getInt(R.styleable.PasswordEditText_count, 4);
        passwordSize = mTypeArray.getInt(R.styleable.PasswordEditText_passwordSize, 24);
        showPassword = mTypeArray.getBoolean(R.styleable.PasswordEditText_showPassword, true);
        bgInputing = mTypeArray.getResourceId(R.styleable.PasswordEditText_bgInputing, R.drawable.bg_inputing);
        bgInputed = mTypeArray.getResourceId(R.styleable.PasswordEditText_bgInputed, R.drawable.bg_inputed);
    }

    /**
     * Description:添加控件,密码框和不可见的输入框
     * Date:2017/8/18
     */
    private void initView() {
        //新建一个容器
        LinearLayout mLinearLayout = new LinearLayout(mContext);
        LinearLayout.LayoutParams linearLayoutParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT);
        mLinearLayout.setLayoutParams(linearLayoutParams);
        mLinearLayout.setOrientation(LinearLayout.HORIZONTAL);

        //根据 count 添加一定数量的密码框
        editTexts = new ArrayList<EditText>();
        LinearLayout.LayoutParams textViewParams = new LinearLayout.LayoutParams(getScreenWidth(mContext) / count - dip2px(mContext, 20), getScreenWidth(mContext) / count - dip2px(mContext, 20));
        textViewParams.setMargins(dip2px(mContext, 10), dip2px(mContext, 10), dip2px(mContext, 10), dip2px(mContext, 10));
        for (int i = 0; i < count; i++) {
            EditText mEditText = new EditText(mContext);
            mEditText.setLayoutParams(textViewParams);
            mEditText.setBackgroundResource(R.drawable.bg_inputed); //设置背景
            mEditText.setGravity(Gravity.CENTER);   //设置文本显示位置
            mEditText.setTextSize(passwordSize);    //设置文本大小
            mEditText.setFocusable(false);  //设置无法获得焦点
            editTexts.add(mEditText);
            mLinearLayout.addView(mEditText);
        }
        editTexts.get(0).setBackgroundResource(bgInputing);

        //添加不可见的 EditText
        LinearLayout.LayoutParams editTextParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT);
        mEditText = new EditText(mContext);
        mEditText.setLayoutParams(editTextParams);
        mEditText.setCursorVisible(false);  //设置输入游标不可见
        mEditText.setBackgroundResource(0); //设置透明背景,让下划线不可见
        mEditText.setAlpha(0.0f);   //设置为全透明,让输入的内容不可见
        mEditText.setInputType(InputType.TYPE_CLASS_NUMBER);    //设置只能输入数字
        mEditText.setFilters(new InputFilter[]{new InputFilter.LengthFilter(count)});   //限制输入长度

        addView(mLinearLayout);
        addView(mEditText);
    }

    /**
     * Description:为输入框添加监听器
     * Date:2017/8/18
     */
    private void addListener() {
        mEditText.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            /**
             *
             * @param s 输入后的文本
             * @param start 输入的位置
             * @param before 输入的位置上之前的字符数
             * @param count 输入的位置上新输入的字符数
             */
            @Override
            public void onTextChanged(CharSequence s, final int start, int before, int count) {
                if (before == 0 && count == 1) {
                    //为对应显示框设置对应显示内容
                    editTexts.get(start).setText(s.subSequence(start, start + 1));
                    //修改输入了内容的密码框的背景
                    editTexts.get(start).setBackgroundResource(bgInputed);
                    //如果还有下一个密码框,将其背景设置为待输入的背景
                    if (start + 1 < editTexts.size()) {
                        editTexts.get(start + 1).setBackgroundResource(bgInputing);
                    } else {
                        //输入完成后关闭软键盘
                        InputMethodManager imm = (InputMethodManager) mContext.getSystemService(
                                Context.INPUT_METHOD_SERVICE);
                        imm.hideSoftInputFromWindow(mEditText.getWindowToken(), 0);
                        //如果添加了监听器,则回调
                        if (mOnCompletionListener != null) {
                            mOnCompletionListener.onCompletion(s.toString());
                        }
                    }
                    //如果需要密文显示,则 0.5s 后设置为密文显示
                    if (!showPassword) {
                        editTexts.get(start).postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                editTexts.get(start).setTransformationMethod(PasswordTransformationMethod.getInstance());
                            }
                        }, 500);
                    }
                    //如果上一个显示框还不是密文显示的话,立即将其设置为密文显示,前提是需要密文显示
                    if (!showPassword && start > 0 && editTexts.get(start - 1).getTransformationMethod() instanceof HideReturnsTransformationMethod) {
                        editTexts.get(start - 1).setTransformationMethod(PasswordTransformationMethod.getInstance());
                    }
                } else if (before == 1 && count == 0) {
                    //清除退格位置对应显示框的内容
                    editTexts.get(start).setText("");
                    //将其退格的位置设置为明文显示
                    editTexts.get(start).setTransformationMethod(HideReturnsTransformationMethod.getInstance());
                    //设置退格位置的背景
                    for (EditText editText : editTexts) {
                        editText.setBackgroundResource(bgInputed);
                    }
                    editTexts.get(start).setBackgroundResource(bgInputing);
                }
            }

            @Override
            public void afterTextChanged(Editable s) {
            }
        });
    }

    public void setOnCompleteListener(onCompletionListener onCompletionListener) {
        this.mOnCompletionListener = onCompletionListener;
    }

    /**
     * Description:获取屏幕宽度
     * Date:2017/8/18
     */
    private int getScreenWidth(Context context) {
        WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
        return wm.getDefaultDisplay().getWidth();
    }

    /**
     * 根据手机的分辨率从 dp 的单位 转成为 px(像素)
     */
    public static int dip2px(Context context, float dpValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dpValue * scale + 0.5f);
    }

    /**
     * 根据手机的分辨率从 px(像素) 的单位 转成为 dp
     */
    public static int px2dip(Context context, float pxValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (pxValue / scale + 0.5f);
    }

    public interface onCompletionListener {
        void onCompletion(String code);
    }
}

这个小东西已经传到 Github 上了,传送门

 

 

自定义密码输入框(passwordEditText) 自定义View 阅读详情

相关推荐

Android进阶之路 - 自定义密码输入框、数字键盘

在项目开发中经常需要自定义输入框和自定义键盘,尤其是涉及修改密码的相关功能;故此学习后进行记录~

Android、前端、小程序、后端 4008

Android EditText的属性详解以及EditText输入密码的格式限制

EditText(输入框),是安卓开发布局时比较常用的控件,和TextView非常类似,最大的区别是:EditText可以接受用户输入。

baipenggui_bo 1万+

Android-MNPasswordEditText类似微信支付宝的密码输入框

MNPasswordEditText 类似微信支付宝的密码输入框

Android EditText 之密码输入框显示和隐藏切换的实现

Android EditText 之密码输入框显示和隐藏切换的实现

leveretz的博客 1216

SAP ABAP BADI_FINS_ACDOC_POSTING_EVENTS 深度应用:KO88工单结算的凭证字段定制与财务数据增强

本文深入探讨了SAP ABAP中BADI_FINS_ACDOC_POSTING_EVENTS在KO88工单结算中的应用,详细解析了如何通过BADI实现财务凭证字段的定制与数据增强。文章提供了从结构扩展到BADI方法实现的完整步骤,包括性能优化建议和实际应用中的测试验证流程,帮助开发人员高效解决企业个性化财务需求。

weixin_26869081的博客 409

ADS许可证配置全攻略:从破解文件放置到环境变量设置(实测有效版)

本文详细介绍了ADS许可证配置的全流程,包括环境准备、全新安装、破解文件部署和环境变量设置等关键步骤。针对常见的安装和授权问题,提供了实测有效的解决方案,帮助工程师快速完成ADS的配置与优化。

websocket5live的博客 398

android自定义金额输入键盘_Android仿支付宝自定义密码输入框及安全键盘(密码键盘)...

0、前言之前做过的项目里有运用到一个支付场景:用户办理业务时需要输入交易密码,并且可根据平台下发的支付方式进行选择。这与支付宝的密码输入方式十分相似,如果使用Android系统或者第三方软件的键盘,会有密码泄露的风险。因此,大多数的应用软件使用的是自定义的密码输入框及安全键盘。由于密码输入方式需要实现一个从底部弹出的效果,因此总体上决定采用BottomSheetDialog来进行封装,同时为了提高...

weixin_32506743的博客 633

从零搭建VGGNet

在 forward 方法中实现了前向传播过程,包括卷积、激活、池化和平铺操作,最后通过全连接层得到分类结果。使用 torch.onnx.export 将模型导出为 ONNX 格式的文件 vgg.onnx。导出 ONNX:将模型导出为 ONNX 格式,便于在其他平台或框架中使用。定义 VGG 网络:构建了一个包含多个卷积层、池化层和全连接层的网络。使用 torch.save 将整个模型保存为 vgg.pth 文件。前向传播:对输入数据进行前向传播,得到输出结果。保存模型:将模型保存为 .pth 文件。

开源驱动,创造价值;坦诚清晰,快速失败;让复杂可计算。 529

推荐一款实用的Android开发工具:PasswordEditText

在Android应用开发中,密码输入框是我们常常遇到的一类组件。然而,原生的`TextInputLayout`和`EditText`有时并不能满足开发者对于安全性和用户体验的高要求。今天,我要向大家推荐一个开源项目——,它为Android开发者提供了一种更加智能且可定制化的密码输入解决方案。 ## 项目简介 `PasswordEditText`是由开发者maksim88创建的一个Android

gitblog_00032的博客 323

Langfuse实战:从评估打分到问题解决的完整指南

本文详细介绍了如何利用开源LLM工程平台Langfuse对AI应用进行系统性评估与优化。从创建评估数据集、设计自动化评分函数,到深入排查常见问题并关联Trace进行精准打分,提供了完整的实战指南。最后,探讨了如何利用评估结果驱动提示词迭代与A/B测试,并给出了生产环境部署与性能优化的关键考量,帮助开发者构建可测量、可分析、可改进的LLM应用。

backprop5master的博客 659

骑砍战团MOD开发(17)-module_scenes.py游戏场景

terrain_code = 单元网格大小(polygon_size) + 地形平面大小(size_x, size_y) + 网格纹理(terrain_layer) + 植被分布(flora_seed) + 河流分布(river_seed).在编辑模式下进入游戏中选择地形可看到地形代码与参数配置。+ 地形(terrain_code+layer_ground_elevation+layer_ground_leveling + layer_color)sf_out_door_scene(室外场景) =

骑砍战团&霸主MOD开发 1219

自定义密码框

效果图 自定义view import android.annotation.SuppressLint; import android.annotation.TargetApi; import android.content.Context; import android.content.res.TypedArray; import android.graphics.Canvas; import android.graphics.Color; import android.graphics...

nsynic的博客 202

大疆FPGA/芯片开发工程师(A卷)笔试题(含详解)

大疆芯片开发岗A卷 一、单选题 1.下列关于多bit数据跨时钟域的处理思路,错误的有   A、发送方给出数据,接收方用本地时钟同步两拍再使用   B、发送方把数据写到异步fifo,接收方从异步fifo里读出   C、对于连续变化的信号,发送方转为格雷码发送,接收方收到后再转为二进制   D、发送方给出数据,发送方给出握手请求,接收方收到后回复,发送方撤销数据 2.对12.918做无损定点化,需要的最小位宽是多少位,位宽选择11位时的量化误差是多少   A、12位,0.0118   B、13位,0.0039

Mr.翟的博客 2万+

Android 自定义EditText

定义一款可清空内容的 EditText 和可显示密码的 EditText,支持修改提示图标和大小、背景图片等。

xiangxiongfly 1445

【CloudCompare教程】017:点云快速全局配准

点云数据的配准分为基于特征(特征点、特征线)的拼接和无特征拼接。特征点匹配的方法和全局ICP的方法。特征点的方法通过全局特征匹配达到全局配准,全局ICP的方法通过对变量空间进行搜索的方法达到全局最优解。

智慧空间实验室 3946

TSN新技术,让您的设备网络“更实时、更确定、更安全”

近日,工业和信息化部发布了2022年第23号公告,批准发布行业标准YD/T 4134-2022《工业互联网时间敏感网络需求及场景》。该标准是国内首个时间敏感网络(TSN)技术标准,标志着我国TSN技术标准体系建设迈出了坚实的一步,对构建工业互联网网络标准体系具有重要意义。TSN源于Time-Sensitive Networking的缩写,中文译名为时间敏感网络,因其具备的确定性和微秒级交互特性,受到了对实时性要求较高的工业控制领域的关注。TSN与工业数智化。

创龙,嵌入式一体化解决方案商 777

Android 密码输入 EditText

最近优化公司的登陆注册,需要能够切换到密码明文,虽然公司另外一个项目有此功能,但是他是用一个EditText 和 一个ImageView 组合成的,虽然说也实现了功能,也没什么问题,但总觉得缺少点程序员的精神,于是就有了下面的密码明文切换的edtitext 项目地址 https://github.com/HuangPugang/PasswordEditText 直接上代码 public

h9911的专栏 1240

InTheHand.Net.Personal+BlueTooth4,蓝牙开发

项目中有蓝牙开发的必备dll,现在网上相关的文档博客不少,有的说的多有的说少,但是却很少有这两个dll,分享一下。

一个带密码显示的EditText

  相信大家都会有遇到过一些最基本的登录或注册业务的场景,里面大多都不可避免地带有一些文本密码输入框。在Android开发中,我们都有用过EditText的控件,但是不同项目每次写又要重新定义一个类似的文本框,就显得有点繁琐,所以倒不如直接给定一个自定义功能的EditText以实现复用。   首先在布局中我们只需要定义我们相关的控件,类似于这样:                        ...

CarsonWoo的博客 536

ET2012新版免狗免安装绿色软件

ET2012新版免狗免安祖昂绿色软件。,新界面,新视觉,

深度学习工具包 DeepLearningToolbox

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain's apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath('DeepLearnToolbox'));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand('state',0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W'); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand('state',0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = 'sigm';%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, 'Too big error');```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand('state',0)sae = saesetup([784 100]);sae.ae{1}.activation_function = 'sigm';sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)')% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = 'sigm';nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, 'Too big error');```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x',28,28,60000))/255;test_x = double(reshape(test_x',28,28,10000))/255;train_y = double(train_y');test_y = double(test_y');%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you'll get around 1.2% errorrand('state',0)cnn.layers = { struct('type', 'i') %input layer struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %sub sampling layer struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, 'Too big error');```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand('state',0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, 'Too big error');%% ex2 neural net with L2 weight decayrand('state',0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex3 neural net with dropoutrand('state',0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex4 neural net with sigmoid activation functionrand('state',0)nn = nnsetup([784 100 10]);nn.activation_function = 'sigm'; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex5 plotting functionalityrand('state',0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = 'softmax'; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand('state',0)nn = nnsetup([784 20 10]); nn.output = 'softmax'; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

Android文本输入框(EditText)输入密码时显示与隐藏

public class MainActivity extends Activity { private Button mSwitchButton; private EditText mPasswordEditText; private boolean isHidden=true; @Override public void onCreate(Bun

bobby_fu的博客 1959

win10 跳过U8环境检测的IE WebControls.rar

win10 安装u8的时候 提示IE WebControls 不通过,这个工具可以欺骗u8的检查。 跳过U8环境检测的IE WebControls。提示导入失败后,重新检测通过。

Kotlin函数详解与使用示例

本文介绍了 Kotlin 函数的核心语法。

TechNomad的博客 300

Kotlin条件语句和循环语句详解

本文介绍了 Kotlin 中常用的条件语句和循环语句。

TechNomad的博客 255

EditText的password属性值(隐藏密码**)

// 显示为普通文本 pwdEdit.setInputType(InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD); // 显示为密码 ** pwdEdit.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);

forLove 3226

如何将EditText设置为密码格式

设置EditText属性inputType即可实现。 属性值: 1、numberPassword,是数字密码格式,只能输入数字。 2、textPassword,实文本密码格式,可以输入任意字符。  ...

kangyuhang1230的博客 7048

推荐项目:MNPasswordEditText - 更安全、更易用的密码输入框

推荐项目:MNPasswordEditText - 更安全、更易用的密码输入框 在开发移动应用时,我们常常需要处理用户的敏感信息,如登录密码。为了确保用户体验和数据安全,选择正确的组件至关重要。今天,我们要推荐一款开源项目——,一个专为Android设计的增强型密码输入控件。 项目简介 MNPasswordEditText是Maning开发的一个Android自定义视图,它继承了EditText并...

gitblog_00075的博客 412

android edittext password 代码,android 之 在代码中改变edittext 的password属性

像wifi连接网络的时候有checkbox,显示密码~在xml 中容易控制inputtype, 在java代码中如下:CheckBox cboBox=(CheckBox)findViewById(R.id.cbox_show); cboBox.setChecked(false); cboBox.setOnCheckedChangeListener(new OnCheckedChangeLi...

weixin_28826521的博客 466

EditText 明文和密码切换

前言我们有些需求,EditText 输入 字符 时 需要 动态切换明文和密码 ,实现方式有两种布局文件布局文件 一个 Relative 包裹 一个EditText 和一个 ImageView ,很简单就不上了。 声明一个变量,控制切换//是否是 密码状态 private boolean isPassWord;方法1if(isPassWord){ ivPwdD

zuochunsheng的博客 745
上一篇: 自定义控件之 Gamepad (游戏手柄)
下一篇: Android Studio 对资源分包
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值