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.
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.
Any help, like always, is greatly appreciated. Feel free to call me an idiot and throw rocks if this is blatantly on Android Developers.
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.) Set an onTouchListener to the TextView.
2.) Get the layout of the TextView.
3.) Get the x,y coordinates of the touch via the event.
4.) Find the line and offset (index) based on that event.
The following code example is how one would Log (in verbose) the index of a touch given a TextView named manip:
EDIT: 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. :-(
1) Take a List.
2)split this string into separate character.
3)take setOnItemClickListener(new OnItemClickListener() ) Event.
4) show Toast for each character by the get args of charcter.
It will help you.
If you're following the accepted answer, you may notice that the
onTouch
event is raised more than once every time the user touches the screen. Useevent.getAction()
to find out what action is being handled. This depends on the user's behaviour that raised the event. For instance, for a simple touch on the screen, theonTouch
event will fire twice with the actionsACTION_DOWN
andACTION_UP
. For a touch and move, you will get different actions depending on the move (within the control, from outside to inside, or vice versa). For more details check the MotionEvent.The following code is a modified version of the accepted answer that only handles the
ACTION_DOWN
action:Take this with a pinch of salt as I had no chance to test it.
Set the
android:textIsSelectable
attribute totrue
for theTextView
and then use thegetSelectionStart()
andgetSelectionEnd()
methods.Again I'm really just making an educated guess.
Following the correct answer above, i add some more features. this way it will also show you the letter that you have clicked, plus it stop the error in case you click outside the boundaries, if you dont put it on try catch, the app will crash.