In Android EditText, how to force writing uppercase?

前端 未结 23 1620
后悔当初
后悔当初 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:41

    Rather than worry about dealing with the keyboard, why not just accept any input, lowercase or uppercase and convert the string to uppercase?

    The following code should help:

    EditText edit = (EditText)findViewById(R.id.myEditText);
    String input;
    ....
    input = edit.getText();
    input = input.toUpperCase(); //converts the string to uppercase
    

    This is user-friendly since it is unnecessary for the user to know that you need the string in uppercase. Hope this helps.

    0 讨论(0)
  • 2020-11-27 12:41

    In kotlin, in .kt file make changes:

    edit_text.filters = edit_text.filters + InputFilter.AllCaps()
    

    Use synthetic property for direct access of widget with id. And in XML, for your edit text add a couple of more flag as:

    <EditText
        android:id="@+id/edit_text_qr_code"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        ...other attributes...
        android:textAllCaps="true"
        android:inputType="textCapCharacters"
        />
    

    This will update the keyboard as upper case enabled.

    0 讨论(0)
  • 2020-11-27 12:42

    Set the input type to TYPE_CLASS_TEXT| TYPE_TEXT_FLAG_CAP_CHARACTERS. The keyboard should honor that.

    0 讨论(0)
  • 2020-11-27 12:43

    Xamarin equivalent of ErlVolton's answer:

    editText.SetFilters(editText.GetFilters().Append(new InputFilterAllCaps()).ToArray());
    
    0 讨论(0)
  • 2020-11-27 12:45

    If you want to force user to write in uppercase letters by default in your EditText, you just need to add android:inputType="textCapCharacters". (User can still manually change to lowercase.)

    0 讨论(0)
  • 2020-11-27 12:52

    You can used two way.

    First Way:

    Set android:inputType="textCapSentences" on your EditText.

    Second Way:

    When user enter the number you have to used text watcher and change small to capital letter.

    edittext.addTextChangedListener(new TextWatcher() {
    
        @Override
        public void onTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {            
    
        }
            @Override
        public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,
                        int arg3) {             
        }
        @Override
        public void afterTextChanged(Editable et) {
              String s=et.toString();
          if(!s.equals(s.toUpperCase()))
          {
             s=s.toUpperCase();
             edittext.setText(s);
             edittext.setSelection(edittext.length()); //fix reverse texting
          }
        }
    });  
    
    0 讨论(0)
提交回复
热议问题