Android EditText with fixed number of max lines and no scrolling

喜你入骨 提交于 2019-12-06 04:53:15

To control the lines introduced you can add a TextWatcher so anytime the user introduces a new value you can handle an error (for example delete the lines after the third one and show a toast). You can check new lines with \r and \n.

http://developer.android.com/reference/android/text/TextWatcher.html

TextWatcher watcher = new TextWatcher() {
    public void afterTextChanged(Editable s) {
      //here you can change edit text and show an error so the lines will never be 3
    }
...}
EditText editText=findById(...);
editText.addTextChangedListener(watcher);;

The attribute maxLines corresponds to the maximum height of the EditText, it controls the outer boundaries and not inner text lines. You'll have to control manually how many characters a user can input into the EditText.

Something like this might work:

mEditText.setOnKeyListener(new View.OnKeyListener() {

        @Override
        public boolean onKey(View v, int keyCode, KeyEvent event) {

            if (keyCode == KeyEvent.KEYCODE_ENTER  && event.getAction() == KeyEvent.ACTION_DOWN) {

                if ( ((EditText)v).getLineCount() > 3 )
                    return true;
                }

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