TextView 中字符串中的 OnClick 位置 [英] OnClick Position in String in TextView

查看:28
本文介绍了TextView 中字符串中的 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 开发者 的公然指责,请随时称我为白痴并扔石头.

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

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

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