user246114
user246114

Reputation: 51691

Set inputType for an EditText Programmatically?

How do we set the input type for an EditText programatically? I'm trying:

mEdit.setInputType(InputType.TYPE_TEXT_VARIATION_PASSWORD);

it doesn't seem to have any effect.

Upvotes: 261

Views: 280743

Answers (17)

Lance Samaria
Lance Samaria

Reputation: 19622

This is based on multiple answers and in Kotlin

1- In my XML file the passwordEditText is initially set to hide the text

<EditText
    android:id="@+id/passwordEditText"
    android:inputType="textPassword" /> // this line hides the text- https://stackoverflow.com/a/48950491/4833705

<Button
    android:id="@+id/toggleButton" />

2- In the Activity, I press the toggleButton to change the passwordEditText's visibility via togglePasswordEditTextVisibity():

binding.toggleButton.setOnClickListener {
    togglePasswordEditTextVisibility()
}

fun togglePasswordEditTextVisibility() {

    val hiddenPassword = InputType.TYPE_CLASS_TEXT or InputType.TYPE_TEXT_VARIATION_PASSWORD
    val visiblePassword = InputType.TYPE_CLASS_TEXT or InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD

    if (binding.passwordEditText.inputType == hiddenPassword) {

        binding.passwordEditText.inputType = visiblePassword
        binding.passwordEditText.transformationMethod = HideReturnsTransformationMethod.getInstance() // https://stackoverflow.com/a/48602018/4833705
        Toast.makeText(this, "Password is now Visible", Toast.LENGTH_SHORT).show()

    } else {

        binding.passwordEditText.inputType = hiddenPassword
        binding.passwordEditText.transformationMethod = PasswordTransformationMethod.getInstance()
        Toast.makeText(this, "Password is now Hidden", Toast.LENGTH_SHORT).show()
    }

    binding.passwordEditText.setSelection(binding.passwordEditText.text.length) // puts the cursor at the end of the text in the EditText because when you change the input type the cursor will be automatically set to the starting point- https://stackoverflow.com/a/9893496/4833705
}

Upvotes: 0

Hesam
Hesam

Reputation: 53610

My answer is not the direct answer to the question. For most of the cases, either of the above answers should be right. However, none of them helped in my case.

I have a custom ViewGroup in my project that contains a text for the Title and an EditText. This EditText receives Texts, Numbers, Password, Phone, etc. depends on the case and place is being used. The Caller of the view group supposed to tell what is the input type.

Important: Setting the inputType should be the last set of the EditText (or at least it has to come after setting the Text of the EditText), otherwise, there is no effect.

enter image description here

Upvotes: 0

Suresh Chaudhary
Suresh Chaudhary

Reputation: 698

InputType will not work, Easiest way is to setTransfromationMethod()

  • To show the Password

     edittextPassword.setTransformationMethod(null);
    
  • To hide the Password Again

     edittextPassword.setTransformationMethod(new PasswordTransformationMethod());
    

Upvotes: 1

Suragch
Suragch

Reputation: 512706

Here are the various Input Types as shown on the standard keyboard.

input types demo

Setting the input type programmatically

editText.setInputType(InputType.TYPE_CLASS_TEXT);

Other options besides TYPE_CLASS_TEXT can be found in the documentation.

Setting the input type in XML

<EditText
    android:inputType="text"
/>

Other options besides text can be found in the documentation.

Supplemental code

Here is the code for the image above.

public class MainActivity extends AppCompatActivity {

    EditText editText;
    TextView textView;
    List<InputTypeItem> inputTypes;
    int counter = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        editText = findViewById(R.id.editText);
        textView = findViewById(R.id.textView);
        initArray();
    }

    public void onChangeInputTypeButtonClick(View view) {
        if (counter >= inputTypes.size()) {
            startOver();
            return;
        }
        textView.setText(inputTypes.get(counter).name);
        editText.setInputType(inputTypes.get(counter).value);
        editText.setSelection(editText.getText().length());
        counter++;
    }

    private void startOver() {
        counter = 0;
        textView.setText("");
        editText.setInputType(InputType.TYPE_CLASS_TEXT);
        InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.hideSoftInputFromWindow(editText.getWindowToken(), 0);
    }


    private void initArray() {
        inputTypes = new ArrayList<>();
        inputTypes.add(new InputTypeItem("date",  InputType.TYPE_CLASS_DATETIME | InputType.TYPE_DATETIME_VARIATION_DATE));
        inputTypes.add(new InputTypeItem("datetime", InputType.TYPE_CLASS_DATETIME | InputType.TYPE_DATETIME_VARIATION_NORMAL));
        inputTypes.add(new InputTypeItem("none", InputType.TYPE_NULL));
        inputTypes.add(new InputTypeItem("number",  InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_VARIATION_NORMAL));
        inputTypes.add(new InputTypeItem("numberDecimal",  InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_DECIMAL));
        inputTypes.add(new InputTypeItem("numberPassword",  InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_VARIATION_PASSWORD));
        inputTypes.add(new InputTypeItem("numberSigned", InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_SIGNED));
        inputTypes.add(new InputTypeItem("phone",  InputType.TYPE_CLASS_PHONE));
        inputTypes.add(new InputTypeItem("text",  InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_NORMAL));
        inputTypes.add(new InputTypeItem("textAutoComplete", InputType.TYPE_TEXT_FLAG_AUTO_COMPLETE));
        inputTypes.add(new InputTypeItem("textAutoCorrect",  InputType.TYPE_TEXT_FLAG_AUTO_CORRECT));
        inputTypes.add(new InputTypeItem("textCapCharacters",  InputType.TYPE_TEXT_FLAG_CAP_CHARACTERS));
        inputTypes.add(new InputTypeItem("textCapSentences",  InputType.TYPE_TEXT_FLAG_CAP_SENTENCES));
        inputTypes.add(new InputTypeItem("textCapWords",  InputType.TYPE_TEXT_FLAG_CAP_WORDS));
        inputTypes.add(new InputTypeItem("textEmailAddress",  InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_EMAIL_ADDRESS));
        inputTypes.add(new InputTypeItem("textEmailSubject", InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_EMAIL_SUBJECT));
        inputTypes.add(new InputTypeItem("textFilter",  InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_FILTER));
        inputTypes.add(new InputTypeItem("textLongMessage",  InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_LONG_MESSAGE));
        inputTypes.add(new InputTypeItem("textMultiLine",  InputType.TYPE_TEXT_FLAG_MULTI_LINE));
        inputTypes.add(new InputTypeItem("textNoSuggestions", InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS));
        inputTypes.add(new InputTypeItem("textPassword",  InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD));
        inputTypes.add(new InputTypeItem("textPersonName", InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PERSON_NAME));
        inputTypes.add(new InputTypeItem("textPhonetic",  InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PHONETIC));
        inputTypes.add(new InputTypeItem("textPostalAddress", InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_POSTAL_ADDRESS));
        inputTypes.add(new InputTypeItem("textShortMessage", InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_SHORT_MESSAGE));
        inputTypes.add(new InputTypeItem("textUri",  InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_URI));
        inputTypes.add(new InputTypeItem("textVisiblePassword",  InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD));
        inputTypes.add(new InputTypeItem("textWebEditText",  InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_WEB_EDIT_TEXT));
        inputTypes.add(new InputTypeItem("textWebEmailAddress", InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_WEB_EMAIL_ADDRESS));
        inputTypes.add(new InputTypeItem("textWebPassword", InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_WEB_PASSWORD));
        inputTypes.add(new InputTypeItem("time", InputType.TYPE_CLASS_DATETIME | InputType.TYPE_DATETIME_VARIATION_TIME));
    }

    class InputTypeItem {
        private String name;
        private int value;
        InputTypeItem(String name, int value) {
            this.name = name;
            this.value = value;
        }
    }
}

See also

Upvotes: 89

Loki
Loki

Reputation: 1378

field.setInputType(InputType.TYPE_CLASS_TEXT);

Upvotes: 0

Alif
Alif

Reputation: 1155

To unhide password:

editText.setInputType(
      InputType.TYPE_CLASS_TEXT|
      InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD
);

To hide password again:

editText.setTransformationMethod(PasswordTransformationMethod.getInstance());

Upvotes: 6

Vibhanshu Sharma
Vibhanshu Sharma

Reputation: 259

password.setInputType(InputType.TYPE_CLASS_TEXT |
InputType.TYPE_TEXT_VARIATION_PASSWORD);

also you have to be careful that cursor moves to the starting point of the editText after this function is called, so make sure that you move cursor to the end point again.

Upvotes: 2

miragessee
miragessee

Reputation: 339

Hide:

edtPassword.setInputType(InputType.TYPE_CLASS_TEXT);
edtPassword.setTransformationMethod(null);

Show:

edtPassword.setInputType(InputType.TYPE_TEXT_VARIATION_PASSWORD);                    
edtPassword.setTransformationMethod(PasswordTransformationMethod.getInstance());

Upvotes: 1

Ronen
Ronen

Reputation: 1285

For Kotlin:

    val password = EditText(this)
    password.inputType = InputType.TYPE_CLASS_TEXT or InputType.TYPE_TEXT_VARIATION_PASSWORD
    password.hint = "Password"

Upvotes: 12

Brian Reinhold
Brian Reinhold

Reputation: 2475

This may be of help to others like me who wanted to toggle between password and free-text mode. I tried using the input methods suggested but it only worked in one direction. I could go from password to text but then I could not revert. For those trying to handle a toggle (eg a show Password check box) use

       @Override
        public void onClick(View v)
        {
            if(check.isChecked())
            {
                edit.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
                Log.i(TAG, "Show password");
            }
            else
            {
                edit.setTransformationMethod(PasswordTransformationMethod.getInstance());
                Log.i(TAG, "Hide password");
            }
        }

I have to credit this for the solution. Wish I had found that a few hours ago!

Upvotes: 6

Amitku
Amitku

Reputation: 4704

For setting the input type for an EditText programmatically, you have to specify that input class type is text.

editPass.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);

Upvotes: 448

pratham kesarkar
pratham kesarkar

Reputation: 3818

I know the expected Answer is in Java . But here's my 2 cents of advice always try to handle view related stuff in XML (atleast basic stuff) so I would suggest rather use a xml attribute rather than handling this use case in java

    <EditText
     android:inputType="textPassword"/>

Upvotes: 0

Ajeet
Ajeet

Reputation: 221

editText.setInputType(EditorInfo.TYPE_CLASS_NUMBER);

//you can change TYPE_... according to your requirement.

Upvotes: 9

skinflint
skinflint

Reputation: 381

i've solve all with

.setInputType(InputType.TYPE_CLASS_NUMBER);

for see clear data and

.setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_VARIATION_PASSWORD);

for see the dots (if the data is a number, it isn't choice che other class)

Upvotes: 36

slinden77
slinden77

Reputation: 3388

To only allow numbers:

password1.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_CLASS_NUMBER);

To transform (hide) the password:

password1.setTransformationMethod(PasswordTransformationMethod.getInstance());

Upvotes: 19

rascalking
rascalking

Reputation: 3460

According to the TextView docs, the programmatic version of android:password is setTransformationMethod(), not setInputType(). So something like:

mEdit.setTransformationMethod(PasswordTransformationMethod.getInstance());

should do the trick.

Upvotes: 226

Jim Blackler
Jim Blackler

Reputation: 23179

Try adding this to the EditText/TextView tag in your layout

android:password="true"

Edit: I just re-read your post, perhaps you need to do this after construction. I don't see why your snippet wouldn't work.

Upvotes: 0

Related Questions