Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
2.5k views
in Technique[技术] by (71.8m points)

android - EditText Minimum Length & Launch New Activity

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...