android how to make text in an edittext exactly fixed lines

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

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



        
4条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-07 05:28

    You cannot do that using any XML attributes.

    maxlines represents the maximum height of the EditText and not the number of input lines.

    You can however implement your own code to check for the number of lines.

    The following is not my own code, but is taken from this answer.

    mEditText.setOnKeyListener(new View.OnKeyListener() {
    
            @Override
            public boolean onKey(View v, int keyCode, KeyEvent event) {
    
                // if enter is pressed start calculating
                if (keyCode == KeyEvent.KEYCODE_ENTER
                        && event.getAction() == KeyEvent.ACTION_UP) {
    
                    // get EditText text
                    String text = ((EditText) v).getText().toString();
    
                    // find how many rows it cointains
                    editTextRowCount = text.split("\\n").length;
    
                    // user has input more than limited - lets do something
                    // about that
                    if (editTextRowCount >= 7) {
    
                        // find the last break
                        int lastBreakIndex = text.lastIndexOf("\n");
    
                        // compose new text
                        String newText = text.substring(0, lastBreakIndex);
    
                        // add new text - delete old one and append new one
                        // (append because I want the cursor to be at the end)
                        ((EditText) v).setText("");
                        ((EditText) v).append(newText);
    
                    }
                }
    
                return false;
            }
    

提交回复
热议问题