1

我想在edittext中有5行,所以用户只能按Enter4次,我试过这样但仍然无法工作

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;
}
});
4

2 回答 2

0

您可以将其中的字符数设置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));
                }
            }
        });
于 2013-02-03T14:20:40.097 回答
0

链接以动态设置编辑文本框的字符长度限制-源代码也可用: http ://www.mobisoftinfotech.com/blog/android/android-edittext-setfilters-example-numeric-text-field-patterns- and-length-restriction/#comment-174948 过滤器和长度限制也可用

于 2013-02-03T13:08:08.150 回答