EditText maxLines不起作用 - 用户仍然可以输入比set更多的行

Ind*_*õue 116 android android-layout android-edittext

<EditText 
    android:id="@+id/editText2" 
    android:layout_height="wrap_content" 
    android:layout_width="fill_parent" 
    android:maxLines="5" 
    android:lines="5">
</EditText>
Run Code Online (Sandbox Code Playgroud)

用户可以按Enter/next行键输入5行以上.如何使用EditText将用户输入限制为固定的行数?

Noe*_*hew 224

<EditText
    android:id="@+id/edit_text"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:inputType="text"
    android:maxLines="1" 
/>
Run Code Online (Sandbox Code Playgroud)

您只需要确保设置了"inputType"属性.没有这条线就行不通.

android:inputType="text"
Run Code Online (Sandbox Code Playgroud)

  • 为我工作.这应该是公认的答案 (11认同)
  • 它仅适用于maxLines 1,但您无法添加新行 (7认同)
  • @byJeevan,我一直认为inputType的默认值为"text".猜猜我错了. (4认同)
  • @Neol周你是对的!我将`inputType`设置为`text`后工作.谢谢你节省我的时间:-) (2认同)
  • 很奇怪,Text 不是为 inputType 设置的默认值,但很好的答案 (2认同)

Ced*_*sme 79

该属性maxLines对应于它的最大高度EditText,它控制外边界而不是内部文本行.

  • 我认为对于开发人员来说,“maxLines”意味着使用 editText 应该可能的最大行数。如果我只想要一个特定的高度,我会使用“线”。:-/ (3认同)

Jes*_*ack 67

这并不能解决限制为n行的一般问题.如果要将EditText限制为只占用一行文本,这可能非常简单.
您可以在xml文件中进行设置.

android:singleLine="true"
Run Code Online (Sandbox Code Playgroud)

或以编程方式

editText.setSingleLine(true);
Run Code Online (Sandbox Code Playgroud)

  • 不推荐使用singleLine (9认同)
  • 但是如果你想限制为2行怎么办?还是3?为此,你必须建立自定义行限制器... (7认同)
  • 我知道这一点."这并不能解决限制为n行的一般问题".当我试图限制为1行并找到一个更简单的解决方案时,我最终阅读了这里的问题.我想其他人可能最终会在这里将EditText限制为1行并实现"自定义行限制器".我的答案是针对其他最终搜索此问题的SO用户,原因与我做的相同. (4认同)
  • editText 的属性 singleLine = "true" 已弃用,并且在大于 7.0 的 Android 上使用的设备会崩溃 (2认同)

Ind*_*õue 23

@Cedekasem你是对的,没有一个内置的"行限制器".但我确实构建了一个自己,所以如果有人感兴趣,代码如下.干杯.

et.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
                int 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;
        }
});
Run Code Online (Sandbox Code Playgroud)


bpa*_*ski 13

我做过像你们一直在寻找的事情.这是我的LimitedEditText课.

特征:

  • 您可以限制LimitedEditText组件中的行数
  • 您可以限制LimitedEditText组件中的字符数
  • 如果你超出文本中间某处的字符或行的限制,光标
    将不会带你到最后 - 它将保持在你去过的地方.

我关闭了监听器,因为setText()在用户超出字符或行限制的情况下,每次调用方法都会递归调用这3个回调方法.

码:

import android.content.Context;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.AttributeSet;
import android.util.Log;
import android.widget.EditText;
import android.widget.Toast;

/**
* EditText subclass created to enforce limit of the lines number in editable
* text field
*/
public class LimitedEditText extends EditText {

/**
 * Max lines to be present in editable text field
 */
private int maxLines = 1;

/**
 * Max characters to be present in editable text field
 */
private int maxCharacters = 50;

/**
 * application context;
 */
private Context context;

public int getMaxCharacters() {
    return maxCharacters;
}

public void setMaxCharacters(int maxCharacters) {
    this.maxCharacters = maxCharacters;
}

@Override
public int getMaxLines() {
    return maxLines;
}

@Override
public void setMaxLines(int maxLines) {
    this.maxLines = maxLines;
}

public LimitedEditText(Context context, AttributeSet attrs, int defStyle) {
    super(context, attrs, defStyle);
    this.context = context;
}

public LimitedEditText(Context context, AttributeSet attrs) {
    super(context, attrs);
    this.context = context;
}

public LimitedEditText(Context context) {
    super(context);
    this.context = context;
}

@Override
protected void onFinishInflate() {
    super.onFinishInflate();

    TextWatcher watcher = new TextWatcher() {

        private String text;
        private int beforeCursorPosition = 0;

        @Override
        public void onTextChanged(CharSequence s, int start, int before,
                int count) {                
            //TODO sth
        }

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count,
                int after) {
            text = s.toString();
            beforeCursorPosition = start;
        }

        @Override
        public void afterTextChanged(Editable s) {

            /* turning off listener */
            removeTextChangedListener(this);

            /* handling lines limit exceed */
            if (LimitedEditText.this.getLineCount() > maxLines) {
                LimitedEditText.this.setText(text);
                LimitedEditText.this.setSelection(beforeCursorPosition);
            }

            /* handling character limit exceed */
            if (s.toString().length() > maxCharacters) {
                LimitedEditText.this.setText(text);
                LimitedEditText.this.setSelection(beforeCursorPosition);
                Toast.makeText(context, "text too long", Toast.LENGTH_SHORT)
                        .show();
            }

            /* turning on listener */
            addTextChangedListener(this);

        }
    };

    this.addTextChangedListener(watcher);
}

}
Run Code Online (Sandbox Code Playgroud)

  • 这个解决方案简单而优雅!谢谢 (2认同)

Osc*_*ata 11

我为此做了更简单的解决方案:D

// set listeners
    txtSpecialRequests.addTextChangedListener(new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            lastSpecialRequestsCursorPosition = txtSpecialRequests.getSelectionStart();
        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {

        }

        @Override
        public void afterTextChanged(Editable s) {
            txtSpecialRequests.removeTextChangedListener(this);

            if (txtSpecialRequests.getLineCount() > 3) {
                txtSpecialRequests.setText(specialRequests);
                txtSpecialRequests.setSelection(lastSpecialRequestsCursorPosition);
            }
            else
                specialRequests = txtSpecialRequests.getText().toString();

            txtSpecialRequests.addTextChangedListener(this);
        }
    });
Run Code Online (Sandbox Code Playgroud)

您可以根据txtSpecialRequests.getLineCount() > 3需要更改3的值.

  • 非常感谢,终于在多个错误的解决方案之后工作了.这应该是公认的答案. (3认同)

Pir*_*ate 5

这是我在我的项目中使用的:

editText.addTextChangedListener(new TextWatcher() {
    private String text;

public void onTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {    
}

public void beforeTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
    text = arg0.toString();
    }

public void afterTextChanged(Editable arg0) {
    int lineCount = editText.getLineCount();
    if(lineCount > numberOfLines){
    editText.setText(text);
    }
}
});

editText.setOnKeyListener(new View.OnKeyListener() {

public boolean onKey(View v, int keyCode, KeyEvent event) {

// if enter is pressed start calculating
    if (keyCode == KeyEvent.KEYCODE_ENTER && event.getAction() == KeyEvent.ACTION_DOWN){    
    int editTextLineCount = ((EditText)v).getLineCount();
    if (editTextLineCount >= numberOfLines)
        return true;
}

return false;
}
});
Run Code Online (Sandbox Code Playgroud)

它适用于所有场景


pec*_*eps 5

这是一个InputFilter,它限制EditText中允许的行:

/**
 * Filter for controlling maximum new lines in EditText.
 */
public class MaxLinesInputFilter implements InputFilter {

  private final int mMax;

  public MaxLinesInputFilter(int max) {
    mMax = max;
  }

  public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
    int newLinesToBeAdded = countOccurrences(source.toString(), '\n');
    int newLinesBefore = countOccurrences(dest.toString(), '\n');
    if (newLinesBefore >= mMax - 1 && newLinesToBeAdded > 0) {
      // filter
      return "";
    }

    // do nothing
    return null;
  }

  /**
   * @return the maximum lines enforced by this input filter
   */
  public int getMax() {
    return mMax;
  }

  /**
   * Counts the number occurrences of the given char.
   *
   * @param string the string
   * @param charAppearance the char
   * @return number of occurrences of the char
   */
  public static int countOccurrences(String string, char charAppearance) {
    int count = 0;
    for (int i = 0; i < string.length(); i++) {
      if (string.charAt(i) == charAppearance) {
        count++;
      }
    }
    return count;
  }
}
Run Code Online (Sandbox Code Playgroud)

要将其添加到EditText:

editText.setFilters(new InputFilter[]{new MaxLinesInputFilter(2)});
Run Code Online (Sandbox Code Playgroud)


bit*_*non 5

最简单的解决方案:

android:maxLines="3"
Run Code Online (Sandbox Code Playgroud)

...

 @Override
public void afterTextChanged(Editable editable) {
    // limit to 3 lines
    if (editText.getLayout().getLineCount() > 3)
        editText.getText().delete(editText.getText().length() - 1, editText.getText().length());
}
Run Code Online (Sandbox Code Playgroud)


naf*_*med 5

你可以根据你的行数来限制你的文本,我说一行大约有 37 个字母

<EditText
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:lines="4"
    android:maxLines="4"
    android:minLines="4"
    android:maxLength="150"
    android:gravity="start"
    android:background="#efeef5"
    android:layout_marginTop="@dimen/pad_10dp"/>
Run Code Online (Sandbox Code Playgroud)


小智 5

设置编辑文本 android:inputType="text"


Adr*_*eto 5

android:inputType="text" (or something different to "none")
android:maxLines="1"  (and this line)
Run Code Online (Sandbox Code Playgroud)