android how to make text in an edittext exactly fixed lines

后端 未结 4 1459
天命终不由人
天命终不由人 2020-12-07 04:34

I want to allow use to enter just 5 lines, I tried this



        
4条回答
  •  -上瘾入骨i
    2020-12-07 05:10

    /** MAX_LINES You want to set */

      public void afterTextChanged(Editable editable) {
            int lines = mEditText.getLineCount();
            if (lines > MAX_LINES) {
                String s = editable.toString();
                int start = mEditText.getSelectionStart();
                int end = mEditText.getSelectionEnd();
    
                if (start == end && start < s.length() && start > 1) {
                    s = s.substring(0, start - 1) + s.substring(start);
                } else {
                    s = s.substring(0, s.length() - 1);
                }
    
                mEditText.setText(s);
                mEditText.setSelection(mEditText.getText().length());
                // Toast.makeText(RatingActivity.this, "max line set to MAX_LINES", Toast.LENGTH_SHORT).show();
      }
    

    This piece of code works for me to set the EditText max lines limit to MAX_LINES.

提交回复
热议问题