我正在尝试为android创建一个定制的pin代码小部件,以替代仅仅使用带有密码inputType属性的inputType。我想要显示的是一行框,并让用户在输入其引脚时填充每个框。
其他人做了类似的事情,但结果却是固定数量的EditText
视图,并且在输入或删除字符时,有许多丑陋的代码用于交换焦点。这不是我想要采取的方法;相反,我正在设计我的可定制长度 (easy),并且表现为一个单个可聚焦视图(不那么容易)。
到目前为止,我的概念是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
,或者让自己的可编辑视图能够提供指导?
(编辑1)在进一步研究了这一点之后,我似乎应该将BaseInputConnection子类并提供一个TextView
或EditText
作为其目标:
@Override
public InputConnection onCreateInputConnection(EditorInfo outAttrs) {
if (!onCheckIsTextEditor()) {
return null;
}
return new BaseInputConnection(mText, true);
}
假设这确实是在输入文本时存储文本,我仍然需要一些方法来更新视图以反映内容的更改.
(编辑2)所以我将这个自定义视图添加到屏幕上进行测试。它显示的框数,整个视图是可聚焦的,但键盘永远不会弹出。我知道它获得了/失去了焦点,因为方框显示了适当的高亮显示,并且我设置了一个要写入logcat的OnFocusChangedListener
。
当可编辑视图获得焦点时,是什么使实际的键盘出现?
发布于 2012-05-12 02:45:36
我在这方面已经取得了很大的进步,不再需要InputConnection的帮助了。简而言之,扩展BaseInputConnection
并重写getEditable()
以返回可编辑的内容。在本例中,我将返回一个由TextView
内部使用的私有PinCodeView
。PinCodeView
还覆盖了一些方法,比如onKey[foo]()
,并将调用转发到内部TextView
。其余的只是使用TextWatcher
来更新文本更改时的子ImageView
之一。
效果真的很好。还有几个小问题有待改进,但我将把它们作为单独的问题来讨论,并在此结束。
发布于 2013-02-08 06:59:21
看起来,您可能正在尝试创建一个类似于pin入口视图/小部件的iOS。
下面是一个很好的示例代码,您可能会发现它很有用。然而,它是固定的长度,但仍然可能对一些人有用。
https://github.com/chinloong/Android-PinView
http://madeveloper.blogspot.com/2013/02/android-ios-like-pin-entrychallenge.html
发布于 2016-12-08 15:58:31
我知道这已经得到了回答,但是由于它的实现不是共享的,所以我找到了一个类似的开源库。它看上去不错,对于那些四处游荡的人来说,它是可以尝试的。
https://stackoverflow.com/questions/10528592
复制相似问题