且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

的OnClick位置在字符串中的TextView

更新时间:2023-11-07 09:56:04

所以,我最终通过在詹姆斯·穆尔的评论here.最后我用了托尼蓝军在这一环节的解决方案。该解决方案是这样的:

So I ended up solving this via the link in James Moore's comment here. I ended up using the Tony Blues's solution in that link. That solution is this:

1)设置onTouchListener到TextView的。

1.) Set an onTouchListener to the TextView.

2)获取的TextView的布局。

2.) Get the layout of the TextView.

3)获取的X,触摸y坐标通过事件。

3.) Get the x,y coordinates of the touch via the event.

4)找到这一行和偏移(指数)的基础上的事件。

4.) Find the line and offset (index) based on that event.

下面code例子是怎么一会登录(以详细)给出一个TextView名为MANIP淡淡的索引:

The following code example is how one would Log (in verbose) the index of a touch given a TextView named manip:

manip.setOnTouchListener(new View.OnTouchListener() {
    public boolean onTouch(View v, MotionEvent event) {
        Layout layout = ((TextView) v).getLayout();
        int x = (int)event.getX();
        int y = (int)event.getY();
        if (layout!=null){
            int line = layout.getLineForVertical(y);
            int offset = layout.getOffsetForHorizontal(line, x);
            Log.v("index", ""+offset);
        }
        return true;
    }
});

编辑:拉胡尔Mandaliya已经把它带到了我的注意,这code会失败,如果有填充的文本视图。不幸的是,它一直是因为我写的任何Android的code很长一段时间,所以我不知道如何更新这个答案来解释这一点。直观地看,好像你可以做一些检查针对click事件的,如果你知道的填充值。很抱歉不能够成为这个边缘情况更有帮助。 : - (

Rahul Mandaliya has brought it to my attention that this code will fail if there is padding on the text view. Unfortunately, it has been a very long time since I've written any Android code, so I'm not sure how to update this answer to account for that. Intuitively, it seems like you could do some sort of check against the click event if you know the padding value. Sorry about not being able to be more helpful on this edge case. :-(