您的位置:首页 > 移动开发 > Android开发

Android 输入框第一次弹出数字键盘, 后面可以随意切换

2017-07-19 22:24 381 查看
转载请注明出处

http://www.jianshu.com/p/1932ff1b78de


前言

记录一次关于 EditText 首次输入需要弹出数字键盘,然后可以随便切换输入模式,下面以 输入身份证号 为例,因为身份证号只可能是数字 + 字母 X,所以这里不仅做了首次弹出数字键盘,还实现了对于其他键盘模式输入做了限制,只能输入字母 X 。


代码

xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.mu_16jj.edittextinputtypedemo.MainActivity">

<EditText
android:id="@+id/et_main"
android:layout_width="300dp"
android:layout_height="45dp"
android:layout_centerHorizontal="true"
android:layout_marginTop="25dp"
android:background="@drawable/sh_et_blue_bg"
android:gravity="center_vertical"
android:hint="第一次打开键盘为数字键盘"
android:paddingLeft="5dp"
android:textColor="@android:color/black" />

</RelativeLayout>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
[/code]

这里没什么可解释的,就一个输入框,需要注意:这里并没有指定输入类型,因为如果指定了输入类型,那么就限定死了。

Java
private void initView() {
setContentView(R.layout.activity_main);
editText = (EditText) findViewById(R.id.et_main);

editText.setKeyListener(listener);
}

KeyListener listener = new NumberKeyListener() {

/**
* @return :返回哪些希望可以被输入的字符,默认不允许输入
*/
@Override
protected char[] getAcceptedChars() {
char[] chars = new char[]{'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'X'};
return chars;
//            return new char[0];
}

/**
* 0:无键盘,键盘弹不出来
* 1:英文键盘
* 2:模拟键盘
* 3:数字键盘
*
* @return
*/
@Override
public int getInputType() {
return 3;
}
};
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
[/code]

这就是核心代码了,主要就是监听,方法的返回值都做了详细的注释说明。在上面代码的情况下,真机运行效果,数字可以随便输入,字母是可以输入大写的 X,其他字符均输入不了。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: