在 edittext 中更改文本之前获取光标起始索引

Get cursor starting index before text changed in edittext

这似乎是一个简单的问题,但我不明白为什么会这样。我想在用户更改文本之前在我的编辑文本中获取 selection 的开始和结束索引,所以在我的TextWatcher 我做了如下操作:-

 public void beforeTextChanged(CharSequence s, int start, int count, int after) {


                    selectionStart = edittext.getSelectionStart();
                    selectionEnd = edittext.getSelectionEnd();


            }

然而 selectionStart 和 selectionEnd return selection.For 示例的结束索引我 select 一个词“你好”两个return 5。我尝试将它们插入处理程序中以在任何键盘输入无济于事之前获得select离子。

我终于找到了这个问题的解决方案,它有点难看,但最好地解决了这个问题。问题是在 textchanged 之前,文本选择已经消失,所以我不得不使用一个处理程序来等待文本被选中,然后跨度观察者像这样立即设置选择:-

final SpanWatcher watcher = new SpanWatcher() {
@Override
public void onSpanAdded(final Spannable text, final Object what,final int start, final int end) {

final Handler handler = new Handler();//handler to get selection after 
certain time
handler.postDelayed(new Runnable() {
@Override
public void run() {

if(noteview.hasSelection()) {

higlightdetect=1;//integer to detect that text was selected

selectionStart = noteview.getSelectionStart();
selectionEnd = noteview.getSelectionEnd();

                    }else
higlightdetect=0;
                }
            }, 600);//after 600ms seemed to be the optimal time after selection occurs
        }
}

@Override
public void onSpanRemoved(final Spannable text, final Object what,
                                  final int start, final int end) {
            // Nothing here.
        }

@Override
public void onSpanChanged(final Spannable text, final Object 
what,final int ostart, final int oend, final int nstart, final int nend) 
{
//The same

final Handler handler = new Handler();//handler to get selection after 
certain time
handler.postDelayed(new Runnable() {
@Override
public void run() {

if(noteview.hasSelection()) {

higlightdetect=1;//integer to detect that text was selected

selectionStart = noteview.getSelectionStart();
selectionEnd = noteview.getSelectionEnd();

                    }else
higlightdetect=0;
                }
            }, 600);//after 600ms seemed to be the optimal time after selection occurs
        }
};


edittext.getText().setSpan(watcher, 0, edittext.length(), Spanned.SPAN_INCLUSIVE_EXCLUSIVE);//set spanwatcher to edittext

当然,这仅在选择文本时有效,不能将其用于常规输入,因为它会在文本更改后立即自动更新,因此在文本观察器中我添加了以下代码:-

@Override
public void beforeTextChanged(CharSequence s, int start, int 
count, int after) {



if(higlightdetect==0){//condition to get cursor position without selection

selectionStart = noteview.getSelectionStart();
selectionEnd=selectionStart;
}
public void onTextChanged(CharSequence s, int start, int before, int 
count) {

        }

@Override
public void afterTextChanged(Editable s) {

Toast.makeText(getthenote.this, String.valueOf(selectionStart), 
Toast.LENGTH_SHORT).show();
Toast.makeText(getthenote.this, String.valueOf(selectionEnd), 
Toast.LENGTH_SHORT).show();

higlightdetect=0 //resetting higlightdetect
}

为什么不直接在 beforeTextChanged 方法中使用 start 参数?