我正在尝试为 android 创建一个自定义 pin 代码小部件,作为仅使用带有密码 inputType 属性的 EditText
的替代方法。我想要显示的是一行框,并在用户键入他的 pin 时填充每个框。
其他人做了类似的事情,但结果是固定数量的 EditText
View ,并且有很多丑陋的代码用于在键入字符时交换焦点或删除。这不是我想要采用的方法;相反,我正在将我的设计设计为具有可自定义的长度(简单)并且表现为单一可聚焦 View (不太容易)。
到目前为止,我的概念是 LinearLayout
(用于容纳“框”)和 EditText
(用于存储用户输入)之间的某种混合体。
这是到目前为止的代码...
public class PinCodeView extends LinearLayout {
protected static final int MAX_PIN_LENGTH = 10;
protected static final int MIN_PIN_LENGTH = 1;
protected int pinLength;
protected EditText mText;
public PinCodeView(Context context, AttributeSet attrs) {
super(context, attrs);
TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.PinCodeView);
try {
pinLength = a.getInt(R.styleable.PinCodeView_pinLength, 0);
} finally {
a.recycle();
}
pinLength = Math.min(pinLength, MAX_PIN_LENGTH);
pinLength = Math.max(pinLength, MIN_PIN_LENGTH);
setupViews();
Log.d(TAG, "PinCodeView initialized with pinLength = " + pinLength);
}
private void setupViews() {
LayoutInflater inflater = (LayoutInflater) getContext().getSystemService(
Context.LAYOUT_INFLATER_SERVICE);
for (int i = 0; i < pinLength; i++) {
// inflate an ImageView and add it
View child = inflater.inflate(R.layout.pin_box, null, false);
addView(child);
}
}
public CharSequence getText() {
// TODO return pin code text instead
return null;
}
public int length() {
// TODO return length of typed pin instead
return pinLength;
}
@Override
public boolean onCheckIsTextEditor() {
return true;
}
@Override
public InputConnection onCreateInputConnection(EditorInfo outAttrs) {
// TODO return an InputConnection
return null;
}
}
关于这些覆盖:onCheckIsTextEditor()应该返回 true 和 onCreateInputConnection(EditorInfo outAttrs)应该返回一个新的 InputConnection
对象来与 InputMethod(键盘)交互,但我只知道这些。
有谁知道我是否在正确的轨道上?有没有人以前使用过 InputConnection
或使他们自己的可编辑 View 能够提供指导?
(编辑 1)
在进一步查看之后,我似乎应该将 BaseInputConnection 子类化并提供一个 TextView
或 EditText
作为其目标:
@Override
public InputConnection onCreateInputConnection(EditorInfo outAttrs) {
if (!onCheckIsTextEditor()) {
return null;
}
return new BaseInputConnection(mText, true);
}
假设这确实存储了键入的文本,我仍然需要一些方法来更新 View 以反射(reflect)内容变化...
(编辑 2)
所以我将这个自定义 View 添加到屏幕进行测试。它显示框的数量,整个 View 是可聚焦的,但键盘永远不会弹出。我知道它获得/失去焦点是因为框适本地突出显示并且我设置了 OnFocusChangedListener
以写入 logcat。
当可编辑 View 获得焦点时,是什么让实际的键盘出现?
最佳答案
看起来您可能正在尝试创建一个类似 iOS 的 pin 输入 View /小部件。
这是一个很好的示例代码,您可能会发现它很有用。然而,它是固定长度的,但对某些人来说仍然有用。
https://github.com/chinloong/Android-PinView
http://madeveloper.blogspot.com/2013/02/android-ios-like-pin-entrychallenge.html
关于android - 自定义 Android 密码输入小部件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10528592/