EditText maxLines가 작동하지 않음-사용자는 여전히 설정된 것보다 더 많은 줄을 입력 할 수 있습니다. android:lines=”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를 사용하여 사용자 입력을 고정 된 행 수로 제한하려면 어떻게해야합니까?



답변

속성 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);
        }
    });

txtSpecialRequests.getLineCount() > 3필요에 따라 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)});