我正在使用EditText小部件,并希望修改用户长按视图时显示的上下文菜单。我遇到的问题是我需要知道长按文本中的字符位置,以便我可以确定我需要添加到上下文菜单中。基类是这样做的,因为菜单中的一个选项是“添加”word_clicked_on“To Dictionary”。在文本中设置ClickableSpans似乎不是一个解决方案,因为它消耗了点击事件,这使得无法在跨度内移动编辑光标。
答案 0 :(得分:4)
这是我提出的解决方案,它确实有效,所以我想分享它:
首先我得出结论,我需要扩展EditText类,以便拦截onTouchEvent,捕获ACTION_DOWN事件并保存位置。现在我有了下降点的位置,我可以调用getOffsetForPosition(downPointX,downPointY)并获取长按的字符位置。有一个大问题,直到SDK 14才添加getOffsetForPosition!为了使这个解决方案工作,如果当前SDK早于SDK_INT 14,我必须支持getOffsetForPosition和branch的功能。这是新类的源代码:
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)
{
// as of SDK 14 the getOffsetForPosition was added to TextView
return getOffsetForPosition(LastDownPositionX, LastDownPositionY);
}
else
{
return GetOffsetForPositionOlderSdk();
}
}
public int GetOffsetForPositionOlderSdk()
{
if (getLayout() == null) return -1;
final int line = GetLineAtCoordinateOlderSDK(LastDownPositionY);
final int offset = GetOffsetAtCoordinateOlderSDK(line, LastDownPositionX);
return offset;
}
public int GetLineAtCoordinateOlderSDK(float y)
{
y -= getTotalPaddingTop();
// Clamp the position to inside of the view.
y = Math.max(0.0f, y);
y = Math.min(getHeight() - getTotalPaddingBottom() - 1, y);
y += getScrollY();
return getLayout().getLineForVertical((int) y);
}
protected int GetOffsetAtCoordinateOlderSDK(int line, float x) {
x = ConvertToLocalHorizontalCoordinateOlderSDK(x);
return getLayout().getOffsetForHorizontal(line, x);
}
protected float ConvertToLocalHorizontalCoordinateOlderSDK(float x) {
x -= getTotalPaddingLeft();
// Clamp the position to inside of the view.
x = Math.max(0.0f, x);
x = Math.min(getWidth() - getTotalPaddingRight() - 1, x);
x += getScrollX();
return x;
}
}
在您的Activity派生类中:
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();
}
});