【问题标题】:Replace EditText selection替换 EditText 选择
【发布时间】:2020-08-16 10:38:24
【问题描述】:

如何用 android 的 edittext 中的内容替换选定的文本? 例如:

Default Text 

假设现在选择“默认”。 我想用 !boldDefault 替换它。 我该怎么做?我尝试使用 get selection 方法,但无法替换它。

【问题讨论】:

    标签: java android string replace android-edittext


    【解决方案1】:

    如果EditText 当前选择了文本,您可以像这样访问选择的起点和终点:

    int start = editText.getSelectionStart();
    int end = editText.getSelectionEnd();
    

    您可以像这样访问EditTextEditable 文本:

    Editable edit = et.getText();
    

    现在您可以使用 replace() 方法替换 Editable 中的任何内容:

    String newText = "this will replace the current selection";
    edit.replace(start, end, newText);
    

    完成此操作后,您可能想要更改选择,以便您没有部分新文本仍然被选中:

    editText.setSelection(start + newText.length());
    

    【讨论】:

    • 感谢您的回答。这正是我想要的。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-02-17
    • 2013-04-25
    • 2017-11-13
    • 2010-11-16
    相关资源
    最近更新 更多