我具有网络视图,单击链接时,我需要为其创建上下文菜单,这是我所做的事情:
protected override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
SetContentView(Resource.Layout.Webview);
wv = (WebView)FindViewById(Resource.Id.WV);
RegisterForContextMenu(wv);
wv.SetWebChromeClient(new WebChromeClient());
wv.SetWebViewClient(new WebViewClient());
wv.Settings.JavaScriptEnabled = true;
wv.Settings.DomStorageEnabled = true;
wv.Settings.SetSupportZoom(true);
wv.Settings.DisplayZoomControls = false;
wv.Settings.BuiltInZoomControls = true;
wv.Settings.CacheMode = CacheModes.Default;
wv.Settings.UseWideViewPort = true;
wv.Settings.LoadWithOverviewMode = true;
wv.SetInitialScale(1);
wv.LoadUrl("file:///android_asset/index.html");
}
public override void OnCreateContextMenu(IContextMenu menu, View v, IContextMenuContextMenuInfo menuInfo)
{
base.OnCreateContextMenu(menu, v, menuInfo);
WebView webView = (WebView)v;
result = webView.GetHitTestResult();
if (result.GetType().ToString().Equals("SRC_ANCHOR_TYPE") || result.GetType().ToString().Equals("ANCHOR_TYPE"))
{
var item = menu.Add("copylink");
item.SetOnMenuItemClickListener(this);
}
}
但是“ result.GetType()”不能检测到锚点类型链接,“ result.GetType()”不能在按下长按时检测到Webview中的任何链接。
如果要向菜单添加项目,则应重写OnActionModeStarted
方法。然后添加类似SetOnMenuItemClickListener
的以下代码。
public override void OnActionModeStarted(ActionMode mode)
{
IMenu menu = mode.Menu;
menu.Add("Add To Notes");
menu.GetItem(0).SetOnMenuItemClickListener(new MyMenuItemOnMenuItemClickListener(this));
base.OnActionModeStarted(mode);
}
internal class MyMenuItemOnMenuItemClickListener : Java.Lang.Object, IMenuItemOnMenuItemClickListener
{
private MainActivity mainActivity;
public MyMenuItemOnMenuItemClickListener(MainActivity mainActivity)
{
this.mainActivity = mainActivity;
}
public bool OnMenuItemClick(IMenuItem item)
{
Toast.MakeText(mainActivity, "You click the Add To Notes", ToastLength.Short).Show();
return true;
}
}
这里正在运行GIF。
如果要创建新菜单,可以使用menu.Clear();
public override void OnActionModeStarted(ActionMode mode)
{
IMenu menu = mode.Menu;
menu.Clear();
menu.Add("Add To Notes");
menu.GetItem(0).SetOnMenuItemClickListener(new MyMenuItemOnMenuItemClickListener(this));
base.OnActionModeStarted(mode);
}
这里正在运行屏幕截图。