Touch coordinates in textview

删除回忆录丶 提交于 2019-11-30 15:37:51

问题


I am using touch listener on text view. I can get the touch coordinates through motion event.

Can I get the character index or near by character coordinates on which I clicked.

Eg., Hello Android

This is my text. Now I can get the x y coordinates but can I get the character index, say A, when I touch it.


回答1:


You have to overide onTouch()

Try with the following

public boolean onTouch(View v, MotionEvent event) {
        // TODO Auto-generated method stub
         Layout layout = ((TextView) v).getLayout();
            int x = (int)event.getX();
            int y = (int)event.getY();
            if (layout!=null){
                int line = layout.getLineForVertical(y);
                int characterOffset = layout.getOffsetForHorizontal(line, x);
                Log.i("index", ""+characterOffset);
                }
            return true;


    }


来源:https://stackoverflow.com/questions/8616064/touch-coordinates-in-textview

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!