<EditText
android:id="@+id/editText2"
android:layout_height="wrap_content"
android:layout_width="fill_parent"
android:maxLines="5"
android:lines="5">
</EditText>
按Enter /下一行键,用户可以输入5行以上。如何使用EditText将用户输入限制为固定的行数?
答案 0 :(得分:196)
<EditText
android:id="@+id/edit_text"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="text"
android:maxLines="1"
/>
您只需要确保设置了“inputType”属性。没有这条线就行不了。
android:inputType="text"
答案 1 :(得分:70)
属性maxLines
对应EditText
的最大高度,它控制外边界而不是内部文本行。
答案 2 :(得分:64)
这不能解决限制为n行的一般问题。如果你想限制你的EditText只需要1行文本,这可以很容易 您可以在xml文件中设置它。
android:singleLine="true"
或以编程方式
editText.setSingleLine(true);
答案 3 :(得分: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;
}
});
答案 4 :(得分:13)
我做了类似你们一直在寻找的事情。这是我的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);
}
}
答案 5 :(得分:10)
我为此做了更简单的解决方案: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);
}
});
您可以根据需要更改txtSpecialRequests.getLineCount() > 3
中的值3。
答案 6 :(得分: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;
}
}
将其添加到EditText:
editText.setFilters(new InputFilter[]{new MaxLinesInputFilter(2)});
答案 7 :(得分:4)
这就是我在项目中使用的内容:
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;
}
});
它适用于所有场景
答案 8 :(得分:3)
这是一种方法。可能会帮助某人。
android:lines="1"
android:maxLines="1"
android:inputType="text
答案 9 :(得分:2)
android:inputType="text" (or something different to "none")
android:maxLines="1" (and this line)
答案 10 :(得分:1)
将EditText
限制为一行的另一种方法如下:
editText2.setTransformationMethod(new SingleLineTransformationMethod());
请注意,应用此转换方法后,回车键会在按下时创建空格。这仍然满足TS&#39;问题
答案 11 :(得分:1)
您可以根据行数限制文本,我说一行中约有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"/>
答案 12 :(得分:1)
设置editText android:inputType="text"
答案 13 :(得分:0)
对于限制字符数,我们可以简单地使用EditText的maxLength属性,因为它不允许用户输入更多字符。
答案 14 :(得分:0)
最简单的解决方案:
android:maxLines="3"
...
@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());
}
答案 15 :(得分:0)
getLineCount()是一个选项;如果您想要非零值,请确保您的视图已被测量。对于软键盘onKeyListener不能工作,所以你必须添加 addTextChangedListener()将在您键入时跟踪文本更改。只要你在其回调中获得足够的行,就可以做任何你想要限制的行:用getText(),setText()删除字符或者更奇特的东西。您甚至可以使用过滤器限制字符数。
另一种选择是使用getLineBounds()监视文本的大小。这将与文本gravity / paddign交互,所以要小心。
答案 16 :(得分:0)
<EditText
android:id="@+id/usrusr"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:gravity="center"
android:lines="1"
android:maxLines="1"
android:inputType="text"
android:hint="@string/inventory_no" />
答案 17 :(得分:0)
另一个想法:每次输入后,仅当行数不超过MAX_LINES时,新文本才会保存到String lastText中。如果是这样,我们可以将EditText的文本设置为最后添加的文本(这样更改将被删除),并通知用户使其简短。
// Set listener to wishDescriptionEditText in order to limit line number
editText.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
@Override
public void afterTextChanged(Editable s) {
// If line account is higher than MAX_LINES, set text to lastText
// and notify user (by Toast)
if (editText.getLineCount() > MAX_LINES) {
editText.setText(lastText);
Toast.makeText(getContext(), "Please keep it short", Toast.LENGTH_LONG).show();
} else {
lastText = editText.getText().toString();
}
}
});
答案 18 :(得分:0)
这是对Indrek Kõue对Kotlin的回答的扩展
Model.deleteMany();
答案 19 :(得分:-4)
尝试在xml文件中使用EditText的以下属性组合:
android:singleLine="true"
android:maxLength="22"