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

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

问题描述

我不知道如何去这样做,但我不知道是否有一种方式来获得在字符串中的位置(索引)在一个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.

任何帮助,像往常一样,大大AP preciated。随时叫我白痴,扔石头,如果这是明目张胆地在 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.

推荐答案

所以,我最终通过在詹姆斯·穆尔的评论<一个链接解决这个href="http://stackoverflow.com/questions/2302867/android-how-to-determine-character-index-of-a-touch-events-position-in-textview">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. :-(

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

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