EditText的光标位置

问题描述:

假设用户已经将一些文本写入了一个文本,然后再触摸屏幕上的其他位置,导致光标位置改变:如何确定新的光标位置?EditText的光标位置

简单的版本:

myEditText.getSelectionStart(); 

如果你想对事件作出反应,你可以尝试

myEditText.setOnTouchListener(new View.OnTouchListener() { 
    @Override 
    public boolean onTouch(View view, MotionEvent event) { 
     // view is myEditText here 
    } 
}); 

event允许按下并释放区分。

EditText也有一个setOnClickListener()这可能是值得一看的。

编辑: 我忘了提及onSelectionChanged(int selStart, int selEnd)其中selEnd等于selStart如果位置改变。

+2

澄清:onSelectionChanged()必须的EditText被子类覆盖是有用的。 OnTouch事件仅在用户真正触摸屏幕时发生。当用户触摸屏幕或通过某些物理输入时,可触发OnClick事件。 D-pad中心,轨迹球点击等。 – greg7gkb 2012-06-21 18:43:08

最好最安全的方法是使用TextWatcher

 @Override 
     public void onTextChanged(CharSequence s, int start, int before, int count) { 
       int cursorIndex = start + 1; 
     }