Here is the solution I came across and it works, so I would like to share it:
First, I came to the conclusion that I need to extend the EditText class so that I can intercept onTouchEvent, grab the ACTION_DOWN event and save the position. Now that I have a low point position, I can call getOffsetForPosition (downPointX, downPointY) and get the position of the character for a long press. There is one big problem: getOffsetForPosition was not added until SDK 14! To make this decision, I had to cancel the port of the getOffsetForPosition function and branches if the current SDK was earlier than SDK_INT 14. Here is the source code for the new class:
public class ScrapEditText extends EditText{ protected float LastDownPositionX, LastDownPositionY; public ScrapEditText(Context context) { super(context); } public ScrapEditText(Context context, AttributeSet attrs) { super(context, attrs); } @Override public boolean onTouchEvent(MotionEvent event) { final int action = event.getActionMasked(); if(action == MotionEvent.ACTION_DOWN) { LastDownPositionX = event.getX(); LastDownPositionY = event.getY(); } return super.onTouchEvent(event); } public float GetLastDownPositionX() { return LastDownPositionX; } public float GetLastDownPositionY() { return LastDownPositionY; } public int GetOffsetForLastDownPosition() { if(Build.VERSION.SDK_INT > 13) {
In the derived Activity class:
ScrapText = (ScrapEditText) findViewById(R.id.sample_text); ScrapText.setOnCreateContextMenuListener(new View.OnCreateContextMenuListener(){ @Override public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) { int charOffset = FileText.GetOffsetForLastDownPosition(); } });
source share