簡體   English   中英

android如何限制edittext的行數

[英]android how to limit the lines on edittext

我想在編輯文本中有5行,因此用戶只能按Enter 4次,我嘗試這樣做,但仍然無法正常工作

myEtidtext.setOnKeyListener(new OnKeyListener() {
    @Override
    public boolean onKey(View v, int keyCode, KeyEvent event) {
    // TODO Auto-generated method stub
    // 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 >= 5) {
            // 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;
}
});

還可以使用鏈接動態設置編輯文本框的字符長度限制-源代碼: http : //www.mobisoftinfotech.com/blog/android/android-edittext-setfilters-example-numeric-text-field-patterns-和長度限制/#comment-174948過濾器和長度限制也可用

您可以將那個EditText的字符數設置為(例如300個字符)。

et_description.addTextChangedListener(new TextWatcher() {

            @Override
            public void onTextChanged(CharSequence s, int start, int before,
                    int count) {
                // TODO Auto-generated method stub
            }

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count,
                    int after) {
                // TODO Auto-generated method stub

            }

            @Override
            public void afterTextChanged(Editable s) {
                // TODO Auto-generated method stub
                if (s.toString().length() > 300) {
                    et_description.setText(s.toString().subSequence(0, 300));
                }
            }
        });

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM