In Android EditText, how to force writing uppercase?

前端 未结 23 1621
后悔当初
后悔当初 2020-11-27 12:28

In my Android application I have different EditText where the user can enter information. But I need to force user to write in uppercase letters. Do you know a

相关标签:
23条回答
  • 2020-11-27 12:58

    A Java 1-liner of the proposed solution could be:

    editText.setFilters(Lists.asList(new InputFilter.AllCaps(), editText.getFilters())
        .toArray(new InputFilter[editText.getFilters().length + 1]));
    

    Note it needs com.google.common.collect.Lists.

    0 讨论(0)
  • 2020-11-27 13:00

    Even better... one liner in Kotlin...

    // gets your previous attributes in XML, plus adds AllCaps filter    
    <your_edit_text>.setFilters(<your_edit_text>.getFilters() + InputFilter.AllCaps())
    

    Done!

    0 讨论(0)
  • 2020-11-27 13:01

    Based on the accepted answer, this answer does the same, but in Kotlin. Just to ease copypasting :·)

    private fun EditText.autocapitalize() {
        val allCapsFilter = InputFilter.AllCaps()
        setFilters(getFilters() + allCapsFilter)
    }
    
    0 讨论(0)
  • 2020-11-27 13:01

    Simple kotlin realization

    fun EditText.onlyUppercase() {
        inputType = InputType.TYPE_CLASS_TEXT or InputType.TYPE_TEXT_FLAG_CAP_CHARACTERS
        filters = arrayOf(InputFilter.AllCaps())
    }
    

    PS it seems that filters is always empty initially

    0 讨论(0)
  • 2020-11-27 13:02

    To get capitalized keyboard when click edittext use this code in your xml,

    <EditText
        android:id="@+id/et"
        android:layout_width="250dp"
        android:layout_height="wrap_content"
        android:hint="Input your country"
        android:padding="10dp"
        android:inputType="textCapCharacters"
        />
    
    0 讨论(0)
提交回复
热议问题