如何从编辑文本中替换特定单词

5 android android-edittext android-textinputedittext

我有一个编辑文本:edittextmysite。

现在我想提供默认文本,例如:“ https://wwww.mysite.com/

我已经实现了如下:

edittextmysite.setText("https://wwww.mysite.com/");
Selection.setSelection(edittextmysite.getText(), edittextmysite.getText().length());


edittextmysite.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (!s.toString().contains("https://wwww.mysite.com/")) {
                    edittextmysite.setText("https://wwww.mysite.com/");
                    Selection.setSelection(edittextmysite.getText(), edittextmysite.getText().length());
                }

            }
        });
Run Code Online (Sandbox Code Playgroud)

因此,如果有人输入文本,它将自动附加到默认值,如下所示:https://wwww.mysite.com/<Mytext>

现在我想要的是如果有人在 edittext 中写下这样的内容:

https://www.mysite.com/https://www.mysite.com/helloworld

或者

https://www.mysite.com/www.mysite.com/helloworld

或者

https://www.mysite.com/www.anyothersite.com/helloworld

它会自动将其转换为正确的格式,如下所示:

https://www.mysite.com/helloworld

我怎样才能实现这个目标?

Vin*_*hod 5

@Override
public void afterTextChanged(Editable s) {
    if (!s.toString().contains("https://wwww.mysite.com/")) {
        String text = s.toString.subString(0, s.lastIndexOf("/"));
        edittextmysite.setText(s.toString().replace(text, "https://wwww.mysite.com/");
        Selection.setSelection(edittextmysite.getText(), edittextmysite.getText().length());
    }
}
Run Code Online (Sandbox Code Playgroud)


The*_*nda 0

与其事后编辑文本,还有许多更好的方法可以实现此目的:

  • 将“ https://example.com/ ”放在编辑文本的左侧,然后如果确实需要,您可以在字符串中搜索 .com、www. 等,并使用任何算法删除它以及它们封装的名称在网上很容易找到。然后连接字符串。

  • 在编辑文本中使用提示。