EditText Minimum Length & Launch New Activity

让人想犯罪 __ 提交于 2019-11-28 09:06:17

问题


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 :)


回答1:


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.



来源:https://stackoverflow.com/questions/7869270/edittext-minimum-length-launch-new-activity

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!