我希望在每次触摸屏幕后获得编辑文本上的光标位置,但是在每次触摸onTouchListener事件之后,它返回的光标位置是先前选择的。
例如,我在文本中选择了位置号59,但得到了结果位置号8。
职位
public class MainActivity extends AppCompatActivity implements View.OnTouchListener {
EditText text;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
text = findViewById(R.id.text);
text.setText("Java is a programming language and computing pla" +
"tform first released by Sun Microsystems in 1995. There are" +
"lots of applications and websites that will not work unless you have Java in" +
"stalled, and more are created every day. Java is fast, secure, and reliable. " +
"From laptops to datacenters, game consoles to scientific supercomputers, cell" +
" phones to the Internet, Java is everywhere!\n");
text.setOnTouchListener(this);
}
@Override
public boolean onTouch(View v, MotionEvent event) {
int start = text.getSelectionStart();
int end = text.getSelectionEnd();
text.append(String.format("\nCurrent selection start=%s end=%s",start, end));
return false;
}
}结果:

发布于 2020-07-07 02:40:17
您可以使用"OnClickListener“来获取光标位置。因为"onTouch“是在光标位置更改之前调用的。
text.setOnClickListener {
val start = text.getSelectionStart()
val end = text.getSelectionEnd()
Log.e("Log", "====>" + start + " " + end)
}https://stackoverflow.com/questions/62767208
复制相似问题