首页 文章

使用Android中的EditText小部件进行屏蔽输入

提问于
浏览
17

有没有办法可以为Android中的EditText控件指定输入掩码?

我希望能够为社会安全号码指定类似### - ## - ####的内容 . 这将导致任何无效输入被自动拒绝(例如,我键入字母字符而不是数字数字) .

我意识到我可以添加一个OnKeyListener并手动检查有效性 . 但这很乏味,我将不得不处理各种边缘情况 .

嗡嗡

6 回答

  • 0

    尝试使用InputFilter而不是 OnKeyListener . 这意味着您不必担心跟踪单个按键操作,它也会处理诸如粘贴到一个字段中的事情,这将很难处理 OnKeyListener .

    您可以查看Android附带的source of the InputFilter implementations,为您提供编写自己的起点 .

  • 1

    你可以看一下android.telephony.PhoneNumberFormattingTextWatcher类 . 它使用### - ### - ####模式屏蔽电话号码文本输入 .

  • 0
    String phoneNumber = "1234567890";
    
    String text = String.valueOf( android.telephony.PhoneNumberUtils.formatNumber(phoneNumber) ); //formatted: 123-456-7890
    
    editTextMobile.setText(text); //set editText text equal to new formatted number
    
    editTextMobile.setSelection(text.length()); //move cursor to end of editText view
    

    onKey 功能中使用此功能可以获得带有格式化电话号码的美味动态兔子性爱 .

  • 20

    我知道在Android Studio的Android程序中使用EditText上的掩码的最简单方法是使用 MaskedEditText 库(GitHub link) . 它's a kind of custom EditText with Watcher that allows you to set a hint with different color (if you want it will be available even when user already started to type), mask and it'非常好用:-)

    compile 'ru.egslava:MaskedEditText:1.0.5'
    
    <br.com.sapereaude.maskedEditText.MaskedEditText
        android:id="@+id/phone_input"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:inputType="phone"
        android:typeface="monospace"
        mask:allowed_chars="1234567"
        mask:mask="###-##-##"
        app:keep_hint="true"
        />
    

    那就是!

    enter image description here

  • 3

    这个site提供了一个很好的2个类,有助于我发现非常有用的掩蔽 .

    您需要使用注释中的项目来改进它 . 但值得添加到您的程序,以便轻松屏蔽许多蒙版的EditText视图 .

  • 2

    你可以在EditText中使用这个efect

    enter image description here

相关问题