Set inputType for an EditText Programmatically?

2019-01-02 20:23发布

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.

标签: android
9条回答
人气声优
2楼-- · 2019-01-02 20:35

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.

查看更多
呛了眼睛熬了心
3楼-- · 2019-01-02 20:39

To only allow numbers:

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

To transform (hide) the password:

password1.setTransformationMethod(PasswordTransformationMethod.getInstance());
查看更多
泪湿衣
4楼-- · 2019-01-02 20:39

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"/>
查看更多
余欢
5楼-- · 2019-01-02 20:41
editText.setInputType(EditorInfo.TYPE_CLASS_NUMBER);

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

查看更多
牵手、夕阳
6楼-- · 2019-01-02 20:45

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!

查看更多
墨雨无痕
7楼-- · 2019-01-02 20:52

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.

查看更多
登录 后发表回答