I'm currently trying to get a custom WebView that displays a ContextMenu when it is pressed for a longer time. As the default WebView class only displays a ContextMenu when a link is longPressed, I wrote my own class to override this behaviour:
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
}
};
}
This works without problems the longPress is detected and the onLongPress method is called, however I am at a loss when it comes to displaying the ContextMenu. I tried doing it the usual way in my 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);
}
However, when I longPress the MyWebView in the emulator, nothing happens. What do I have to call from onLongPress() to display the ContextMenu?
Call Activity.openContextMenu(View v) in onLongPress. This would mean having the MyWebView keep a reference to the Activity though.