怎么在Android中通过自定义view实现一个输入控件?很多新手对此不是很清楚,为了帮助大家解决这个难题,下面小编将为大家详细讲解,有这方面需求的人可以来学习下,希望你能有所收获。
首先是ImageView的子类TextImageView,onDraw的实现也很简单,就是判断text是否长度大于0,如果大于0则绘制文字,还有一些细节处理就是设置字体颜色,字体大写,获取字体的宽高
@Override
protected void onDraw(Canvas canvas) {
if (text.length() > 0) {
if (isDrawSrc) {
super.onDraw(canvas);
}
canvas.drawText(text, 0, text.length(), (getMeasuredWidth() - textWidth) / 2, (getMeasuredHeight() + dy) / 2, textPaint);
} else {
super.onDraw(canvas);
}
}
其次PasswordView是一个自定义ViewGroup,引入了一个布局,布局中就是一个EditText(数据捕捉)和一个Linearlayout(代码添加TextImageView)。EditText的宽高是1dp和0dp(避免用户可以操作EditText);给Linearlayout设置divider属性(两个TextImageView的间隔)
PasswordView的核心代码如下:
- 代码控制EditView获取输入
public void requestEtFocus() {
catchInput.setFocusable(true);
catchInput.setFocusableInTouchMode(true);
catchInput.setClickable(true);
catchInput.requestFocus();
showSoftKeyboard(catchInput);
catchInput.setCursorVisible(false);
catchInput.setSelection(catchInput.length());
}
// 动态添加TextImageView
for (int i = 0; i < passwordLength; i++) {
TextImageView view = new TextImageView(context);
view.setTextSize(textSize);
view.setTextColor(textColor);
content.addView(view);
if (unInputBg != 0) {
view.setBackgroundResource(unInputBg);// 设置未输入前的背景
}
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams((int) itemWidth, (int) itemHeight);
if (i == 0) {
params.setMargins((int) dpToPixel(1), 0, 0, 0);
}
if (i == passwordLength - 1) {
params.setMargins(0, 0, (int) dpToPixel(1), 0);
}
view.setLayoutParams(params);
views[i] = view;
// 分割字体,给TextIamgeView绘制文字
if (text != null && i < text.length()) {
setItemText(text.subSequence(i, i + 1));
}
}
// 输入监听
catchInput.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
if (s.length() > 0) {
// index:成员变量;保存当前的输入了几个字符
if (index > s.length()) {
removeItemText();// 删除
} else {
setText(s);
if (s.length() == passwordLength) {
if (listener != null) {
// 输入完成回调
listener.onInputCodeEnd(s);
}
}
}
} else if (s.length() == 0 && index > 0) {
removeItemText();
}
}
@Override
public void afterTextChanged(Editable s) {
}
});
Android是一种基于Linux内核的自由及开放源代码的操作系统,主要使用于移动设备,如智能手机和平板电脑,由美国Google公司和开放手机联盟领导及开发。
看完上述内容是否对您有帮助呢?如果还想对相关知识有进一步的了解或阅读更多相关文章,请关注亿速云行业资讯频道,感谢您对亿速云的支持。
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。