6

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

 3 years ago
source link: http://www.androidchina.net/6880.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
Android 输入框第一次弹出数字键盘, 后面可以随意切换 – Android开发中文站
你的位置:Android开发中文站 > Android开发 > 开发进阶 > Android 输入框第一次弹出数字键盘, 后面可以随意切换

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

<?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>

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

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;
        }
    };

这就是核心代码了,主要就是监听,方法的返回值都做了详细的注释说明。在上面代码的情况下,真机运行效果,数字可以随便输入,字母是可以输入大写的 X,其他字符均输入不了。

转载请注明出处
http://www.jianshu.com/p/1932ff1b78de

转载请注明:Android开发中文站 » Android 输入框第一次弹出数字键盘, 后面可以随意切换


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK