<EditText
android:id="@+id/editText2"
android:layout_height="wrap_content"
android:layout_width="fill_parent"
android:maxLines="5"
android:lines="5">
</EditText>
用户可以按回车/下一行键输入5行以上。如何使用EditText将用户输入限制为固定的行数?
<EditText
android:id="@+id/editText2"
android:layout_height="wrap_content"
android:layout_width="fill_parent"
android:maxLines="5"
android:lines="5">
</EditText>
用户可以按回车/下一行键输入5行以上。如何使用EditText将用户输入限制为固定的行数?
Answers:
该属性maxLines
对应于的最大高度EditText
,它控制外部边界,而不控制内部文本行。
<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"
inputType
为以后,我就工作了text
。感谢您节省我的时间:-)
这不能解决限制为n行的一般问题。如果您想将EditText限制为仅接受1行文本,这可能非常容易。
您可以在xml文件中进行设置。
android:singleLine="true"
或以编程方式
editText.setSingleLine(true);
@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;
}
});
我做了一些像你们一直在寻找的事情。这是我的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);
}
}
beforeCursorPosition = getSelectionStart();
在afterTextChanged
回调中。效果更好,因为键入e
后键入时abcd
,EditText可能会“认为”您替换abcd
为abcde
,因为输入法的原因。
我为此做了更简单的解决方案: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 in的值。
这是一个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)});
这是我在项目中使用的:
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;
}
});
它适用于所有情况
设置editText android:inputType="text"
最简单的解决方案:
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());
}
android:inputType="text" (or something different to "none")
android:maxLines="1" (and this line)
将您的EditText
一行限制为另一种方式是:
editText2.setTransformationMethod(new SingleLineTransformationMethod());
请注意,应用此转换方法后,按Enter键会创建空格。这仍然可以满足TS的问题。
您可以根据行数限制文本,我说一行中约有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"/>
<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" />
另一个想法:每次输入后,仅当行数不超过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();
}
}
});
这是IndrekKõue对Kotlin 的扩展
input_name.addTextChangedListener(object : TextWatcher {
override fun afterTextChanged(s: Editable?) {}
override fun beforeTextChanged(
s: CharSequence?,
start: Int,
count: Int,
after: Int
) {
}
@SuppressLint("SetTextI18n")
override fun onTextChanged(
s: CharSequence?,
start: Int,
before: Int,
count: Int
) {
val text = (input_name as EditText).text.toString()
val editTextRowCount = input_name.lineCount
if (editTextRowCount > 15) {
val newText = text.substring(0, text.length - 1)
input_name.setText("")
input_name.append(newText)
}
}
})