EditText maxLines가 작동하지 않습니다-사용자는 여전히 설정보다 많은 라인을 입력 할 수 있습니다
<EditText
android:id="@+id/editText2"
android:layout_height="wrap_content"
android:layout_width="fill_parent"
android:maxLines="5"
android:lines="5">
</EditText>
Enter / Next Row 키를 누르면 5 줄 이상을 입력 할 수 있습니다. EditText를 사용하여 사용자 입력을 고정 된 행 수로 제한하려면 어떻게해야합니까?
이 속성 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"
이것은 n 라인으로 제한하는 일반적인 문제를 해결하지 못합니다. 한 줄의 텍스트 만 사용하도록 EditText를 제한하려는 경우 매우 쉽습니다.
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
수업이 있습니다.
풍모:
- 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);
}
}
나는 이것을 위해 더 간단한 해결책을 만들었다 : 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);
}
});
3 값을 txtSpecialRequests.getLineCount() > 3
필요에 따라 변경할 수 있습니다 .
다음은 EditText에서 허용되는 줄을 제한하는 InputFilter입니다.
/**
* 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;
}
});
그리고 그것은 모든 시나리오에서 작동했습니다
this is one approach. Might help someone.
android:lines="1"
android:maxLines="1"
android:inputType="text
Simplest solution:
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());
}
Another way to limit your EditText
to one line is the following:
editText2.setTransformationMethod(new SingleLineTransformationMethod());
Note that after applying this transformation method, the enter key creates spaces when pressed. That still satisfies TS' question.
You can limit your text according to your no of lines i say around 37 alphabets in one line
<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"/>
getLineCount() is one option; if you want non-zero values there make sure your view is measured. For soft keyboard onKeyListener won't work so you have to add addTextChangedListener() that will track text changes as you type. As soon as you get enough lines inside its call backs do whatever you want to limit it: delete characters with getText(), setText() or something more fancy. You can even limit the number of characters using a filter.
Another option is to monitor size of the text with getLineBounds(). This will interact with text gravity/paddign so be careful.
For limit number of characters we can simply use maxLength property of EditText as it will not allow user to enter more characters.
<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" />
Try using the following combination of attributes of the EditText inside the xml file:
android:singleLine="true"
android:maxLength="22"
'programing tip' 카테고리의 다른 글
foreach 루프에서 배열 요소를 어떻게 제거합니까? (0) | 2020.07.23 |
---|---|
안드로이드 장치를 확인하는 방법은 HDPI 화면 또는 MDPI 화면입니까? (0) | 2020.07.22 |
보고서를 작성할 때 "보고서 데이터"창이 표시되지 않는 이유는 무엇입니까? (0) | 2020.07.22 |
System.Drawing.Color를 RGB 및 16 진수 값으로 변환 (0) | 2020.07.22 |
스위프트 : 열거 형 값을 문자열로 변환 하시겠습니까? (0) | 2020.07.22 |