EditText의 텍스트 끝에 커서를 놓습니다.
나는의 값을 변경하고 EditText
의를 keyListener
.
하지만 텍스트를 변경하면 커서가 EditText
. 커서가 텍스트 끝에 있어야합니다.
어떻게 텍스트의 끝으로 커서를 이동합니다 EditText
.
이 시도:
EditText et = (EditText)findViewById(R.id.inbox);
et.setSelection(et.getText().length());
현재 edittext 값에 문자열 값을 추가하고 값 끝에 커서를 두는 ediitext에 대한 append라는 함수가 있습니다. 현재 ediitext 값 자체로 문자열 값을 가질 수 있으며 append ();
myedittext.append("current_this_edittext_string");
Kotlin :
커서를 시작 위치 로 설정합니다 .
val editText = findViewById(R.id.edittext_id) as EditText
editText.setSelection(0)
커서를 EditText 끝으로 설정하십시오 .
val editText = findViewById(R.id.edittext_id) as EditText
editText.setSelection(editText.getText().length())
아래 코드는 두 번째 문자 뒤에 커서를 놓는 것입니다 .
val editText = findViewById(R.id.edittext_id) as EditText
editText.setSelection(2)
자바 :
커서를 시작 위치 로 설정합니다 .
EditText editText = (EditText)findViewById(R.id.edittext_id);
editText.setSelection(0);
커서를 EditText 끝으로 설정하십시오 .
EditText editText = (EditText)findViewById(R.id.edittext_id);
editText.setSelection(editText.getText().length());
아래 코드는 두 번째 문자 뒤에 커서를 놓는 것입니다 .
EditText editText = (EditText)findViewById(R.id.edittext_id);
editText.setSelection(2);
setText
이전에 호출 했는데 새 텍스트가 setSelection
별도의 실행 파일에서 레이아웃 단계 호출 을 받지 못한 경우 View.post(Runnable)
( 이 주제 에서 다시 게시 ).
그래서 나를 위해이 코드는 작동합니다.
editText.setText("text");
editText.post(new Runnable() {
@Override
public void run() {
registerPhone.setSelection("text".length());
}
});
2019 년 5 월 16 일 수정 : 현재 Kotlin 확장 프로그램을 사용하고 있습니다.
fun EditText.placeCursorToEnd() {
this.setSelection(this.text.length)
}
그런 다음-editText.placeCursorToEnd ().
다음 EditText
과 같이보기 의 텍스트 끝에 커서를 놓을 수도 있습니다 .
EditText et = (EditText)findViewById(R.id.textview);
int textLength = et.getText().length();
et.setSelection(textLength, textLength);
editText.setOnKeyListener(new View.OnKeyListener() {
@Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
editText.setSelection(editText.getText().length());
return false;
}
});
이것은 또 다른 가능한 해결책입니다.
et.append("");
어떤 이유로 든 작동하지 않으면이 솔루션을 시도하십시오.
et.setSelection(et.getText().length());
EditText의 setSelection () 메서드를 사용하여이를 달성 할 수 있어야합니다. 여기를 참조 하십시오.
제 경우에는 다음 kotlin ext를 만들었습니다. 기능, 누군가에게 유용 할 수 있음
private fun EditText.focus(){
requestFocus()
setSelection(length())
}
그런 다음 다음과 같이 사용하십시오.
mEditText.focus()
/**
* Set cursor to end of text in edittext when user clicks Next on Keyboard.
*/
View.OnFocusChangeListener onFocusChangeListener = new View.OnFocusChangeListener() {
@Override
public void onFocusChange(View view, boolean b) {
if (b) {
((EditText) view).setSelection(((EditText) view).getText().length());
}
}
};
mEditFirstName.setOnFocusChangeListener(onFocusChangeListener);
mEditLastName.setOnFocusChangeListener(onFocusChangeListener);
그것은 나를 위해 잘 작동합니다!
나는 이것이 당신이 원하는 것을 얻을 수 있다고 생각합니다.
Editable etext = mSubjectTextEditor.getText();
Selection.setSelection(etext, etext.length());
질문은 오래되고 답변되었지만 새로 출시 된 Android 용 DataBinding 도구를 사용하려는 경우이 답변을 사용하는 것이 유용 할 수 있다고 생각합니다.
<data>
<variable name="stringValue" type="String"/>
</data>
...
<EditText
...
android:text="@={stringValue}"
android:selection="@{stringValue.length()}"
...
/>
EditText가 명확하지 않은 경우 :
editText.setText("");
editText.append("New text");
안녕하세요 시도해보세요
<EditText
android:id="@+id/edt_text"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Hello World!"
android:cursorVisible="true"/>
EditText editText = findViewById(R.id.editText); editText.setSelection(editText.getText().length()); // End point
커서
모든 텍스트를 선택하고 이전 텍스트 대신 새 텍스트를 입력하려면 다음을 사용할 수 있습니다.
android:selectAllOnFocus="true"
이것은 작동합니다
Editable etext = edittext.getText();
Selection.setSelection(etext,edittext.getText().toString().length());
editText.setSelection
여기에 마법이 있습니다. 기본적으로 선택하면 원하는 위치에 커서를 놓을 수 있습니다.
EditText editText = findViewById(R.id.editText);
editText.setSelection(editText.getText().length());
그러면 커서가 EditText 끝에 배치됩니다. 기본적으로 editText.getText().length()
텍스트 길이를 제공합니다. 그런 다음 setSelection
길이로 사용 합니다.
editText.setSelection(0);
시작 위치 (0)에 커서를 설정하기위한 것입니다.
내가 테스트 한 다른 모든 코드는 사용자가 여전히 문자열 중간에 캐럿 / 커서를 둘 수 있다는 사실 때문에 잘 작동하지 않았습니다 (예 : 12 | 3.00-여기서 |는 커서). 내 솔루션은 EditText에서 터치가 발생할 때마다 항상 커서를 문자열 끝에 놓습니다.
궁극적 인 솔루션은 다음과 같습니다.
// For a EditText like:
<EditText
android:id="@+id/EditTextAmount"
android:layout_height="wrap_content"
android:layout_width="fill_parent"
android:hint="@string/amount"
android:layout_weight="1"
android:text="@string/zero_value"
android:inputType="text|numberDecimal"
android:maxLength="13"/>
@ string / amount = "0.00"@ string / zero_value = "0.00"
// Create a Static boolean flag
private static boolean returnNext;
// Set caret/cursor to the end on focus change
EditTextAmount.setOnFocusChangeListener(new View.OnFocusChangeListener() {
@Override
public void onFocusChange(View editText, boolean hasFocus) {
if(hasFocus){
((EditText) editText).setSelection(((EditText) editText).getText().length());
}
}
});
// Create a touch listener and put caret to the end (no matter where the user touched in the middle of the string)
EditTextAmount.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View editText, MotionEvent event) {
((EditText) editText).onTouchEvent(event);
((EditText) editText).setSelection(((EditText) editText).getText().length());
return true;
}
});
// Implement a Currency Mask with addTextChangedListener
EditTextAmount.addTextChangedListener(new TextWatcher() {
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
String input = s.toString();
String output = new String();
String buffer = new String();
String decimals = new String();
String numbers = Integer.toString(Integer.parseInt(input.replaceAll("[^0-9]", "")));
if(returnNext){
returnNext = false;
return;
}
returnNext = true;
if (numbers.equals("0")){
output += "0.00";
}
else if (numbers.length() <= 2){
output += "0." + String.format("%02d", Integer.parseInt(numbers));
}
else if(numbers.length() >= 3){
decimals = numbers.substring(numbers.length() - 2);
int commaCounter = 0;
for(int i=numbers.length()-3; i>=0; i--){
if(commaCounter == 3){
buffer += ",";
commaCounter = 0;
}
buffer += numbers.charAt(i);
commaCounter++;
}
output = new StringBuilder(buffer).reverse().toString() + "." + decimals;
}
EditTextAmount.setText(output);
EditTextAmount.setSelection(EditTextAmount.getText().length());
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
/*String input = s.toString();
if(input.equals("0.0")){
EditTextAmount.setText("0.00");
EditTextAmount.setSelection(EditTextAmount.getText().length());
return;
}*/
}
@Override
public void afterTextChanged(Editable s) {
}
});
도움이 되었기를 바랍니다.
이것은 안전하게 트릭을 수행합니다 .
editText.setText("");
if (!TextUtils.isEmpty(text)) {
editText.append(text);
}
@Anh Duy의 답변과 비슷하지만 저에게는 효과가 없었습니다. 또한 사용자가 편집 텍스트를 탭하고 나중에 커서의 위치를 선택할 수있을 때만 커서가 끝으로 이동해야했습니다. 이것이 저를 위해 일한 유일한 코드입니다.
boolean textFocus = false; //define somewhere globally in the class
//in onFinishInflate() or somewhere
editText.setOnTouchListener(new OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
editText.onTouchEvent(event);
if(!textFocus) {
editText.setSelection(editText.getText().length());
textFocus = true;
}
return true;
}
});
editText.setOnFocusChangeListener(new OnFocusChangeListener() {
@Override
public void onFocusChange(View v, boolean hasFocus) {
textFocus = false;
}
});
public class CustomEditText extends EditText {
public CustomEditText(Context context, AttributeSet attrs) {
super(context, attrs);
}
public CustomEditText(Context context) {
super(context);
}
public CustomEditText(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
@Override
protected void onFocusChanged(boolean focused, int direction, Rect previouslyFocusedRect) {
super.onFocusChanged(focused, direction, previouslyFocusedRect);
this.setSelection(this.getText().length());
}
@Override
protected void onSelectionChanged(int selStart, int selEnd) {
}
}
XML 파일에서이 CustomEditText를 사용하면 작동합니다. 나는 이것을 테스트했고 그것은 나를 위해 일하고 있습니다.
EditText보기에서 텍스트 끝에 커서를 두려면
EditText rename;
String title = "title_goes_here";
int counts = (int) title.length();
rename.setSelection(counts);
rename.setText(title);
etSSID.setSelection(etSSID.getText().length());
ViewModel, LiveData 및 데이터 바인딩의 경우
EditText
내 노트 앱에서 여러 줄 지원을 위해이 기능이 필요했습니다 . 사용자가 메모 텍스트가있는 조각으로 이동할 때 텍스트 끝에 커서를두고 싶었습니다.
djleop 이 제안한 해결책 이 가깝습니다. 하지만 문제는 사용자가 편집을 위해 텍스트 중간에 커서를 놓고 입력을 시작하면 커서가 다시 텍스트 끝으로 이동한다는 것입니다. 이는 LiveData
에서 새 값을 내보내고 커서가 다시 텍스트 끝으로 이동하여 사용자가 중간 어딘가에서 텍스트를 편집 할 수 없기 때문에 발생했습니다.
이를 해결하기 위해 플래그를 사용하여 한 번만 MediatorLiveData
길이를 사용 하고 할당합니다 String
. 이렇게하면 사용자가 조각으로 이동할 때 LiveData가 값을 한 번만 읽습니다. 그 후 사용자는 텍스트를 편집하려는 곳에 커서를 놓을 수 있습니다.
ViewModel
private var accessedPosition: Boolean = false
val cursorPosition = MediatorLiveData<Event<Int>>().apply {
addSource(yourObject) { value ->
if(!accessedPosition) {
setValue(Event(yourObject.note.length))
accessedPosition = true
}
}
}
여기에 표시 yourObject
중인 문자열 텍스트를 보유하는 데이터베이스에서 검색된 또 다른 LiveData가 있습니다 EditText
.
그런 다음 MediatorLiveData
바인딩 어댑터를 사용하여이를 EditText에 바인딩하십시오.
XML
텍스트를 표시하고 텍스트 입력을 수락하기 위해 양방향 데이터 바인딩을 사용합니다.
<!-- android:text must be placed before cursorPosition otherwise we'll get IndexOutOfBounds exception-->
<EditText
android:text="@={viewModel.noteText}"
cursorPosition="@{viewModel.cursorPosition}" />
바인딩 어댑터
@BindingAdapter("cursorPosition")
fun bindCursorPosition(editText: EditText, event: Event<Int>?) {
event?.getContentIfNotHandled()?.let { editText.setSelection(it) }
}
Event
수업
Event
여기에 있는 클래스는 Google의 Jose Alcérreca가 작성한 SingleLiveEvent 와 같습니다 . 여기에서 화면 회전을 처리하는 데 사용합니다. 싱글 Event
을 사용하면 사용자가 텍스트를 중간에 편집하고 화면이 회전 할 때 커서가 텍스트 끝으로 이동하지 않도록합니다. 화면이 회전 할 때 동일한 위치를 유지합니다.
Event
수업 은 다음과 같습니다 .
open class Event<out T>(private val content: T) {
var hasBeenHandled = false
private set // Allow external read but not write
/**
* Returns the content and prevents its use again.
*/
fun getContentIfNotHandled(): T? {
return if (hasBeenHandled) {
null
} else {
hasBeenHandled = true
content
}
}
/**
* Returns the content, even if it's already been handled.
*/
fun peekContent(): T = content
}
이것은 나를 위해 작동하고 좋은 사용자 경험을 제공하는 솔루션입니다. 프로젝트에도 도움이되기를 바랍니다.
EditText editText=findViewById(R.id.et_id);
editText.requestFocus();
참고 URL : https://stackoverflow.com/questions/6217378/place-cursor-at-the-end-of-text-in-edittext
'Development Tip' 카테고리의 다른 글
다른 브랜치에서 Git에 브랜치 만들기 (0) | 2020.09.28 |
---|---|
MySQL의 여러 열에 대한 고유 제약 조건을 어떻게 지정합니까? (0) | 2020.09.28 |
MySQL 데이터베이스의 테이블 크기를 얻는 방법은 무엇입니까? (0) | 2020.09.28 |
Visual Studio 프로젝트 속성의 다양한 "빌드 작업"설정은 무엇이며 어떤 역할을합니까? (0) | 2020.09.28 |
특정 버전의 루비 보석을 설치하는 방법은 무엇입니까? (0) | 2020.09.28 |