Android - EditText 行數控制

摘要:Android - EditText 行數控制


	/**
	 * enter key  countrol / lines control
	 */
	private OnKeyListener editOnkeyListener = 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
                int editTextRowCount = text.split("\n").length;

                // user has input more than limited - lets do something
                // about that
                if (editTextRowCount >= MAX_LINES) {                    

                    // 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;
        }
	};

 

EditText 的maxLines,並不是真的限制可輸入的長度列數,他只是外框的長度最大值,但並不是輸入的長度行數值。

因此需要用onKey,按下Enter時,做判斷處理。