Android:在自定义WebView中从onLongPress打开ContextMenu
作者:互联网
我目前正在尝试获取一个自定义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
}
};
}
这可以正常工作,检测到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);
}
但是,当我在模拟器中长按MyWebView时,没有任何反应.我需要从onLongPress()调用什么来显示ContextMenu?
解决方法:
在onLongPress中调用Activity.openContextMenu(View v).这意味着让MyWebView保持对Activity的引用.
标签:android,webview,contextmenu,gesturedetector 来源: https://codeday.me/bug/20190518/1128866.html