Android:在自定义WebView中从onLongPress打开ContextMenu

jba*_*ter 5 android contextmenu webview gesturedetector

我目前正在尝试获取一个自定义WebView,当它被按下较长时间时会显示一个ContextMenu.由于默认WebView类仅在链接为longPressed时显示ContextMenu,因此我编写了自己的类来覆盖此行为:

public class MyWebView extends WebView {
    Context context;
    GestureDetector gd;

    public MyWebView(Context context, AttributeSet attributes) {
        super(context, attributes);
        this.context = context;
        gd = new GestureDetector(context, sogl);
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        return gd.onTouchEvent(event);
    }

    GestureDetector.SimpleOnGestureListener sogl =
                new GestureDetector.SimpleOnGestureListener() {

        public boolean onDown(MotionEvent event) {
            return true;
        }

        public void onLongPress(MotionEvent event) {
            // The ContextMenu should probably be called here
        }
    };
}
Run Code Online (Sandbox Code Playgroud)

这可以正常工作,检测到longPress并调用onLongPress方法,但是在显示ContextMenu时我不知所措.我尝试在我的Activity中按照惯例进行操作:

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.layout);

    MyWebView mwv = (MyWebView) findViewById(R.id.mwv);
    registerForContextMenu(mwv);
}

@Override
public void onCreateContextMenu(ContextMenu menu, View v,
                    ContextMenu.ContextMenuInfo menuInfo) {
    super.onCreateContextMenu(menu, v, menuInfo);
    MenuInflater inflater = getMenuInflater();
    inflater.inflate(R.menu.context, menu);
}
Run Code Online (Sandbox Code Playgroud)

但是,当我在模拟器中长按MyWebView时,没有任何反应.我需要从onLongPress()调用什么来显示ContextMenu?

gng*_*r44 1

在onLongPress中调用Activity.openContextMenu(View v)。这意味着 MyWebView 保留对 Activity 的引用。