Android controls EditText input content type

For example, the control input box can only enter numbers:


The first is to use attribute control in the xml file

                    <EditText
                        android:id="@+id/login_input_num_et"
                        android:layout_width="0dp"
                        android:layout_height="wrap_content"
                        android:layout_gravity="center_vertical"
                        android:layout_weight="1"
                        android:background="@null"
                        android:digits="0123456789"
                        android:hint="@string/login_01"
                        android:inputType="number"
                        android:maxLength="10"
                        android:paddingLeft="13dp"
                        android:paddingTop="1dp"
                        android:paddingRight="13dp"
                        android:paddingBottom="1dp"
                        android:singleLine="true"
                        android:textColor="@color/se_0000"
                        android:textColorHint="@color/se_bcbf"
                        android:textSize="12sp"
                        android:textStyle="bold" />

The second, through code dynamic control


 login_input_num_et.addTextChangedListener(NumChangeListener())

    inner class NumChangeListener : TextWatcher {
        override fun beforeTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {

        }

        override fun onTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {
            val editable: String = getNum()
            val str = accountFilter(editable)
            if (editable != str) {
                login_input_num_et.setText(str)
                login_input_num_et.setSelection(str!!.length)
            }
        }

        override fun afterTextChanged(p0: Editable?) {

        }

    }

    fun accountFilter(str: String?): String? {
        // 只允许数字
        val regEx = "[^0-9]"
        val p: Pattern = Pattern.compile(regEx)
        val m: Matcher = p.matcher(str)
        return m.replaceAll("").trim()
    }

 Another matching rule:
such as:
only numbers and letters can be entered val regEx = "[^a-zA-Z0-9]"

Only numbers, letters, and designated symbols can be entered val regEx = "[^a-zA-Z0-9@_.]"
(numbers, letters, @ _ ​​.)

Guess you like

Origin blog.csdn.net/NewActivity/article/details/123431451