文本选择取决于 phone

Text selection depending on the phone

在我的应用程序中,我有一个 EditText,用户可以在其中 select 部分文本。问题是 selection 行为因 phone 而异:对于一个,用户可以正常 select,但对于另一个,用户必须点击文本指示器,然后点击 "Select All".

如何将第一个行为设置为默认行为?为什么 phones 之间的行为不同?

感谢您的回答,祝您愉快!

编辑:

现在我select包含光标的单词用这个方法:

fun EditText.selectCurrentWord() {
    val textSpan = text
    val selection = selectionStart
    val pattern = Pattern.compile("\w+")
    val matcher = pattern.matcher(textSpan)
    var start: Int
    var end: Int

    while (matcher.find()) {
        start = matcher.start()
        end = matcher.end()

        if (selection in start..end) {
            setSelection(start, end)
            break
        }
    }
}

但是现在的问题是 selection 开始和结束的光标没有出现...

EditText select可用并且 isCursorVisible 设置为 true。

您可以尝试使用 Button 到 select 使用

的文本
EditText myET = findViewById(R.id.myET);
Button selectBtn = findViewById(R.id.selectBtn);

selectBtn.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        myET.setSelectAllOnFocus(true);
        myET.selectAll();    
    }
});

您可以使用

打开context menu
openContextMenu(myET);

还可以获取光标的起点和终点位置

myET.getSelectionStart();
myET.getSelectionEnd();

参考答案

  1. Getting cursor position

更新 1

在你的按钮点击中添加这个,这似乎有效,但有时你必须点击 2 次你可以调整这个

myET.performLongClick();
myET.setSelection(0, myET.length());

希望这会有所帮助!