Android 如何在 EditText 中禁用光标定位和文本选择?(安卓)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11170409/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-20 06:13:10  来源:igfitidea点击:

How to disable cursor positioning and text selection in an EditText? (Android)

androidandroid-edittexttextselectionandroid-cursor

提问by Louis

I'm searching for a way to prevent the user from moving the cursor position anywhere. The cursor should always stay at the end of the current EditText value. In addition to that the user should not be able to select anything in the EditText. Do you have any idea how to realize that in Android using an EditText?

我正在寻找一种方法来防止用户将光标位置移动到任何地方。光标应始终停留在当前 EditText 值的末尾。除此之外,用户不应该能够在 EditText 中选择任何内容。您知道如何在 Android 中使用 EditText 实现这一点吗?

To clarify: the user should be able to insert text, but only at the end.

澄清:用户应该能够插入文本,但只能在最后。

回答by mikejonesguy

I had the same problem. This ended up working for me:

我有同样的问题。这最终对我有用:

public class CustomEditText extends EditText {

    @Override
    public void onSelectionChanged(int start, int end) {

        CharSequence text = getText();
        if (text != null) {
            if (start != text.length() || end != text.length()) {
                setSelection(text.length(), text.length());
                return;
            }
        }

        super.onSelectionChanged(start, end);
    }

}

回答by Hein

This will reset cursor focus to the last position of the text

这会将光标焦点重置到文本的最后一个位置

editText.setSelection(editText.getText().length());

This method will disable cursor move on touch

此方法将禁用触摸时光标移动

public class MyEditText extends EditText{

    @Override
    public boolean onTouchEvent(MotionEvent event)
    {
         final int eventX = event.getX();
         final int eventY = event.getY();
         if( (eventX,eventY) is in the middle of your editText)
         {
              return false;
         }
         return true;
    }
}

And You can use either the xml attribute

你可以使用 xml 属性

android:cursorVisible

android:cursorVisible

or the java function

或 java 函数

setCursorVisible(boolean)

setCursorVisible(布尔值)

to disable blinking cursor of edittext

禁用编辑文本的闪烁光标

回答by Jason Lin

Try this:

尝试这个:

mEditText.setMovementMethod(null);

回答by Alex Lockwood

It sounds like the best way to do this is to make your own CustomEditTextclass and override/modify any relevant methods. You can see the source codefor EditTexthere.

听起来最好的方法是创建自己的CustomEditText类并覆盖/修改任何相关方法。你可以看到源代码,EditText在这里。

public class CustomEditText extends EditText {

    @Override
    public void selectAll() {
        // Do nothing
    }

    /* override other methods, etc. */

}