How to force edittext to write in uppercase in android

In android if we want to type uppercase letters on edittext, there is one button on keyboard to change the keyboard state to uppercase, But what if we want our edittext to accept only uppercase letters. In this tutorial we will learn how to implement EditText which will accept only uppercase letters in android.

There are different ways for achieving this functionality. One way is to set filter to edittext in java file, another way is to set it in xml file and in another way we can change each character to uppercase which typing.

Contents

  • Solution 1 – Setting filter in java file
  • Solution 2 – setting directly in xml file
  • Setting in TextChangeListener

Solution 1

Add the following line to your java file in which edittext is used.

your_edit_text.setFilters(new InputFilter[]{new InputFilter.AllCaps()});

Solution 2

Add the following line to the EditText widget in your xml file.

android:inputType="textCapCharacters"

Your EditText will become

<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="textCapCharacters"
/>

Solution 3

Add the following code to your java file in which edittext is used.

your_edit_text.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {

}

@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {

}

@Override
public void afterTextChanged(Editable arg) {

String s = arg.toString();
if(!s.equals(s.toUpperCase())){
s = s.toUpperCase();
your_edit_text.setText(s);
your_edit_text.setSelection(your_edit_text.getText().length());

}

}
});

You can use any one of the above three solutions for achieving the same.

About the author

Hi guys, i am the author of codesfor. I am a B.Tech graduate currently working as an App developer. Apart from job i am a blogger and a freelancer.

Add a Comment

Your email address will not be published. Required fields are marked *