首页 > 解决方案 > 文本选择取决于手机

问题描述

在我的应用程序中,我有一个 EditText,用户可以在其中选择部分文本。问题是选择行为因手机而异:使用一个,用户可以正常选择,但另一个用户必须点击文本指示器,然后点击“全选”。

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

感谢您的回答,祝您有美好的一天!

编辑 :

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

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

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

EditText 是可选择的并isCursorVisible设置为 true。

标签: androidandroid-edittext

解决方案


您可以尝试使用 aButton来选择文本

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. 获取光标位置

  2. 以编程方式选择文本

更新 1

将其添加到您的按钮单击中,这似乎可行,但有时您必须单击 2 次才能调整它

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

希望这会有所帮助!


推荐阅读