【问题标题】:How to find the position of Cursor to select text from that position in Edit text?如何在编辑文本中找到光标的位置以从该位置选择文本?
【发布时间】:2023-03-13 00:15:01
【问题描述】:

我正在为 android 设备开发键盘,我是文本编辑选项,如谷歌键盘(文本选择、复制粘贴等)。 例如,我输入了一个文本 ABSCEONDER,现在我想选择文本的某些部分。就像我想从 E 位置选择文本一样。我所做的是我手动将光标放在 E 位置。现在我如何找到光标的位置以从该位置选择文本?有人可以帮忙吗?

 ExtractedText extractedText = mLatinIme.getCurrentInputConnection().getExtractedText(new ExtractedTextRequest(), 0);
                if (extractedText == null || extractedText.text == null) return;
                int index = extractedText.text.length();
                mLatinIme.getCurrentInputConnection().setSelection(0, index);

【问题讨论】:

    标签: java android android-softkeyboard richtextediting inputconnection


    【解决方案1】:

    您可以像这样从EditText 获取光标位置:

    editText.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) {
    
                  int pos = editText.getSelectionStart();
                  Layout layout = editText.getLayout();
                  float x = layout.getPrimaryHorizontal(pos);
    
                }
            });
    

    【讨论】:

    • 兄弟,如果它在输入连接中?如果我们在手机上输入消息,那么我如何找到位置?
    • 如果我使用 int pos=mLatinIme.getCurrentInputConnection() 那么 getstartselection 不起作用。
    【解决方案2】:

    谢谢@mohammadReza Abiri。我找到了解决方案。

     ExtractedText extractedText = mLatinIme.getCurrentInputConnection().getExtractedText(new ExtractedTextRequest(), 0);
            if (extractedText == null || extractedText.text == null) return;
    
            int selectionStart = extractedText.selectionStart;
            int selectionEnd = extractedText.selectionEnd;
    
            mLatinIme.getCurrentInputConnection().setSelection(selectionStart, selectionEnd + 1);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-04-14
      • 2011-02-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-10-06
      • 1970-01-01
      • 2016-08-01
      相关资源
      最近更新 更多