我正在使用 EditText 小部件,并且想修改当用户长按 View 时显示的上下文菜单。我遇到的问题是我需要知道长按文本中的字符位置,这样我才能确定我需要添加到上下文菜单中的内容。基类这样做是因为菜单中的选项之一是“将“word_clicked_on”添加到词典”。在文本中设置 ClickableSpans 似乎不是解决方案,因为它会消耗单击事件,这使得无法在跨度内移动编辑光标。
最佳答案
这是我想出的解决方案,它确实有效,所以我想分享它:
首先我得出结论,我需要扩展 EditText 类,以便我可以拦截 onTouchEvent,捕获 ACTION_DOWN 事件,并保存位置。现在我有了向下点的位置,我可以调用 getOffsetForPosition(downPointX, downPointY) 并获取长按的字符位置。有个大问题,getOffsetForPosition 是SDK 14才加入的!为了使这个解决方案起作用,如果当前 SDK 早于 SDK_INT 14,我必须向后移植 getOffsetForPosition 和分支的功能。这是新类的源代码:
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();
}
});
关于android - 基于长按位置动态修改 EditText 中的上下文/长按菜单,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9096613/