将光标放在EditText中文本的末尾

问题描述 投票:792回答:24

我正在改变EditTextkeyListener的价值。

但是当我改变文本时,光标移动到EditText的开头。我需要光标位于文本的末尾。

如何将光标移动到EditText中文本的末尾。

android android-edittext keylistener
24个回答
1225
投票

试试这个:

EditText et = (EditText)findViewById(R.id.inbox);
et.setSelection(et.getText().length());

10
投票
/**
 * 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);

它对我有用!


9
投票

我认为这可以实现你想要的。

 Editable etext = mSubjectTextEditor.getText();
 Selection.setSelection(etext, etext.length());

7
投票

如果您的EditText不清楚:

editText.setText("");
editText.append("New text");

7
投票

这个问题已经过时并且已经回答了,但我认为如果您想使用Android最新发布的DataBinding工具,只需在XML中设置它就可能有用这个答案:

<data>
    <variable name="stringValue" type="String"/>
</data>
...
<EditText
        ...
        android:text="@={stringValue}"
        android:selection="@{stringValue.length()}"
        ...
/>

5
投票

enter image description here

你好试试这个

 <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 pointCursor


4
投票

如果要选择所有文本并只输入新文本而不是旧文本,则可以使用

    android:selectAllOnFocus="true"

4
投票

这有效

Editable etext = edittext.getText();
Selection.setSelection(etext,edittext.getText().toString().length());

4
投票

editText.setSelection是这里的魔力。基本上选择可以将光标放在您想要的任何位置。

EditText editText = findViewById(R.id.editText);
editText.setSelection(editText.getText().length());

这将光标放在EditText的末尾。基本上editText.getText().length()给你文字长度。然后你使用setSelection长度。

editText.setSelection(0);

用于将光标设置在起始位置(0)。


3
投票

我测试的所有其他代码都不能正常工作,因为用户仍然可以将插入符号/光标放在字符串中间的任何位置(例如: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) {

            }
        });

希望能帮助到你!


2
投票

这可以安全地解决问题:

    editText.setText("");
    if (!TextUtils.isEmpty(text)) {
        editText.append(text);
    }

210
投票

有一个名为append for ediitext的函数,它将字符串值附加到当前的edittext值,并将光标放在值的末尾。您可以将字符串值作为当前ediitext值本身并调用append();

myedittext.append("current_this_edittext_string"); 

1
投票

类似于@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;
    }
});

0
投票

如果要将光标放在EditText视图中的文本末尾

 EditText rename;
 String title = "title_goes_here";
 int counts = (int) title.length();
 rename.setSelection(counts);
 rename.setText(title);

0
投票
etSSID.setSelection(etSSID.getText().length());

-1
投票
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,这将起作用。我测试了这个,它对我有用。


-3
投票
EditText editText=findViewById(R.id.et_id);

editText.requestFocus();

111
投票

科特林:

将光标设置为起始位置:

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())

Code下面是将光标放在第二个字符后面:

val editText = findViewById(R.id.edittext_id) as EditText
editText.setSelection(2)

JAVA:

将光标设置为起始位置:

 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());

Code下面是将光标放在第二个字符后面:

EditText editText = (EditText)findViewById(R.id.edittext_id);
editText.setSelection(2);

68
投票

如果您之前调用setText并且新文本没有得到布局阶段调用setSelection在由View.post(Runnable)this主题转发)的单独runnable中调用。

所以,对我来说这个代码有效:

editText.setText("text");
editText.post(new Runnable() {
         @Override
         public void run() {
             registerPhone.setSelection("text".length());
         }
});

编辑05/16/2019:现在我正在使用Kotlin扩展:

fun EditText.placeCursorToEnd() {
    this.setSelection(this.text.length)
}

然后 - editText.placeCursorToEnd()。


40
投票

您也可以将光标放在EditText视图中文本的末尾,如下所示:

EditText et = (EditText)findViewById(R.id.textview);
int textLength = et.getText().length();
et.setSelection(textLength, textLength);

26
投票
editText.setOnKeyListener(new View.OnKeyListener() {
    @Override
    public boolean onKey(View v, int keyCode, KeyEvent event) {
        editText.setSelection(editText.getText().length());
        return false;
    }
});

19
投票

这是另一种可能的解决方案

et.append("");

如果它因任何原因不起作用,请尝试此解决方案:

et.setSelection(et.getText().length());

11
投票

您应该可以使用EditText的方法setSelection()来实现它,请参阅here


11
投票

在我的情况下,我创建了以下kotlin ext。功能,可能对某人有用

 private fun EditText.focus(){
        requestFocus()
        setSelection(length())
    }

然后使用如下

mEditText.focus()
© www.soinside.com 2019 - 2024. All rights reserved.