Android 自定义输入支付密码的软键盘
有项目需求需要做一个密码锁功能,还有自己的软键盘,类似与支付宝那种,这里是整理的资料,大家可以看下,如有错误,欢迎留言指正
需求:要实现类似支付宝的输入支付密码的功能,效果图如下:
软键盘效果图
使用 android.inputmethodservice.KeyboardView这个类自定义软键盘
软键盘的实现
1. 自定义只输入数字的软键盘 PasswordKeyboardView 类,继承自 android.inputmethodservice.KeyboardView
/**
* 输入数字密码的键盘布局控件。
*/
public class PasswordKeyboardView extends KeyboardView implements
android.inputmethodservice.KeyboardView.OnKeyboardActionListener {
// 用于区分左下角空白的按键
private static final int KEYCODE_EMPTY = -10;
private int mDeleteBackgroundColor;
private Rect mDeleteDrawRect;
private Drawable mDeleteDrawable;
private IOnKeyboardListener mOnKeyboardListener;
public PasswordKeyboardView(Context context, AttributeSet attrs) {
super(context, attrs);
init(context, attrs, 0);
}
public PasswordKeyboardView(Context context, AttributeSet attrs,
int defStyleAttr) {
super(context, attrs, defStyleAttr);
init(context, attrs, defStyleAttr);
}
private void init(Context context, AttributeSet attrs,
int defStyleAttr) {
TypedArray a = context.obtainStyledAttributes(attrs,
R.styleable.PasswordKeyboardView, defStyleAttr, 0);
mDeleteDrawable = a.getDrawable(
R.styleable.PasswordKeyboardView_pkvDeleteDrawable);
mDeleteBackgroundColor = a.getColor(
R.styleable.PasswordKeyboardView_pkvDeleteBackgroundColor,
Color.TRANSPARENT);
a.recycle();
// 设置软键盘按键的布局
Keyboard keyboard = new Keyboard(context,
R.xml.keyboard_number_password);
setKeyboard(keyboard);
setEnabled(true);
setPreviewEnabled(false);
setOnKeyboardActionList