Welcome to 16892 Developer Community-Open, Learning,Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I have a couple of queries regarding the EditText function in Android.

First of all, is it possible to set a minimum number of characters in the EditText field? I'm aware that there is an

android:maxLength="*"

however for some reason you can't have

android:minLength="*"

Also, I was wondering if it is possible to launch a new activity after pressing the enter key on the keyboard that pops us when inputing data into the EditText field? And if so, could someone show me how?

Thanks for any help you could offer regarding either question :)

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
2.3k views
Welcome To Ask or Share your Answers For Others

1 Answer

To respond to an enter key in your edit field and notify the user if they haven't entered enough text:

EditText myEdit = (EditText) findViewById(R.id.myedittext);
    myEdit.setOnKeyListener(new OnKeyListener() {
        public boolean onKey(View v, int keyCode, KeyEvent event) {
            if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER)) {
                if (myEdit.getText().length() < minLength) {
                    Toast.makeText(CurrentActivity.this, "Not enough characters", Toast.LENGTH_SHORT);
                } else {
                    startActivity(new Intent(CurrentActivity.this, ActivityToLaunch.class);
                }
                return true;
            }
            return false;
        }
    });

There's no simple way to force a minimum length as the field is edited. You'd check the length on every character entered and then throw out keystrokes when the user attempt to delete past the minimum. It's pretty messy which is why there's no built-in way to do it.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to 16892 Developer Community-Open, Learning and Share
...