文本视图中字符串中的 OnClick 位置 [英] OnClick Position in String in TextView

查看:23
本文介绍了文本视图中字符串中的 OnClick 位置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不知道该怎么做,但是我想知道当一个人单击 TextView 上的某个位置时,是否有办法在 TextView 中的字符串中获取位置(索引).所以,如果有人点击下面的TextView:

I'm not sure how to go about doing this, but I was wondering if there was a way to get the position (index) in a String in a TextView when a person clicks somewhere on the TextView. So, if someone clicks on the following TextView:

Hello I'm Vinay Hiremath.

在第一个H"上,onClick 事件将获得整数 0.或者,如果有人单击V",它将获得 10,依此类推.

on the first 'H', the onClick event will get the integer 0. Or, if someone clicks on the 'V', it will get 10, and so on.

任何帮助,像往常一样,非常感谢.如果这在 Android Developers 上公然出现,请随意称我为白痴并扔石头.

Any help, like always, is greatly appreciated. Feel free to call me an idiot and throw rocks if this is blatantly on Android Developers.

推荐答案

所以我最终通过 James Moore 评论中的链接解决了这个问题 这里.我最终在该链接中使用了 Tony Blues 的解决方案.该解决方案是这样的:

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.) 为 TextView 设置一个 onTouchListener.

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.

以下代码示例是如何在给定名为 manip 的 TextView 的情况下记录(详细)触摸的索引:

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;
    }
});

Rahul Mandaliya 提醒我注意,如果文本视图上有填充,则此代码将失败.不幸的是,我已经很长时间没有编写任何 Android 代码了,所以我不确定如何更新这个答案来解决这个问题.直观地说,如果您知道填充值,您似乎可以对点击事件进行某种检查.很抱歉不能在这个边缘案例上提供更多帮助.:-(

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. :-(

这篇关于文本视图中字符串中的 OnClick 位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆