简体   繁体   中英

Android EditText - InputType Validation?

Created a AlertDialog that is used to prompting the user to enter a keyword. Problem is that I don't want the keyword to have any symbols in it, so I though that doing

input.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_NORMAL);

Might do that, but for some reason on my 1.6 API level 4 emulator it doesn't seem to work, it lets me enter everything. Am I doing it right? I've googled around and everyone else's seems to work.

Here is custom edit box listener that allows only alphanumeric characters.

package com.iperia.android.listener;

import android.text.Editable;
import android.text.InputType;
import android.text.method.NumberKeyListener;
import android.view.View;

public class AlphanumericPasswordKeyListener extends NumberKeyListener
{
    @Override
    protected char[] getAcceptedChars()
    {       
        return new char [] { '1', '2', '3', '4', '5', '6', '7', '8', '9', '0',
                             'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 
                             'k', 'l', 'm', 'n', 'o', 'p', 'q', 'e', 's', 't', 
                             'u', 'v', 'w', 'x', 'y', 'z', 
                             'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 
                             'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'E', 'S', 'T', 
                             'U', 'V', 'W', 'X', 'Y', 'Z'};
    }

    @Override
    public void clearMetaKeyState(View view, Editable content, int states)
    {

    }

    @Override
    public int getInputType()
    {   
        return InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD;
    }   
}

Then in your activity in onCreate method add next code:

EditText passwordEditText = (EditText)findViewById(R.id.password);
passwordEditText.setKeyListener(new AlphanumericPasswordKeyListener());

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM