检测特定URL并更改活动 [英] Detect specific URL and change activity
问题描述
我一直在尝试找到一种方法,可以用来检测WebView中的特定URL,然后启动另一个Activity。以下是代码:
I have been trying to find a way that can be used to detect a specific URL in a WebView and then start another Activity. Following is the code:
public class ClientWebView : WebViewClient
{
public override bool ShouldOverrideUrlLoading(WebView view, string url)
{
view.LoadUrl(url);
return true;
}
public override void OnPageStarted(WebView view, string url, Bitmap favicon)
{
progressDialog.Show();
if(url=="http://test-domain.com")
StartActivity(typeof(MainActivity));
base.OnPageStarted(view, url, favicon);
}
public override void OnPageFinished(WebView view, string url)
{
base.OnPageFinished(view, url);
}
public override void OnReceivedError(WebView view, IWebResourceRequest request, WebResourceError error)
{
base.OnReceivedError(view, request, error);
}
}
但是我知道在WebViewClient中无法使用StartActivity,因为我收到以下错误An非静态字段,方法或属性'Context.StartActivity(Type)'需要对象引用。任何人都可以指导我解决方案吗?
我尝试过:
我试过用string url = webView.URL获取webview的url。但是我再次陷入如何开始另一项活动。
But I know StartActivity cannot be used in WebViewClient as I get the following error "An object reference is required for the non-static field, method or property 'Context.StartActivity(Type)'". Can Anyone please guide me with the solution?
What I have tried:
I have tried getting url of the webview with "string url= webView.URL;" but again i get stuck at how to start another activity.
推荐答案
我能够通过对课程进行以下更改来解决这个问题:
I was able to solve it by making following changes to the class:
public class ClientWebView : WebViewClient
{
private Context context;
public ClientWebView(Context context)
{
this.context = context;
}
public override bool ShouldOverrideUrlLoading(WebView view, string url)
{
view.LoadUrl(url);
return true;
}
public override void OnPageStarted(WebView view, string url, Bitmap favicon)
{
progressDialog.Show();
if (url.Equals("https://test.com/"))
{
var intent = new Intent(context, typeof(MainActivity));
context.StartActivity(intent);
}
base.OnPageStarted(view, url, favicon);
}
public override void OnPageFinished(WebView view, string url)
{
if (progressDialog != null)
{
progressDialog.Hide();
}
base.OnPageFinished(view, url);
}
public override void OnReceivedError(WebView view, IWebResourceRequest request, WebResourceError error)
{
webView.Visibility = ViewStates.Invisible;
dialog.Show();
base.OnReceivedError(view, request, error);
}
}
然后在我的oncreate方法中添加以下内容:
and then added following in my oncreate method:
webView.SetWebViewClient(new ClientWebView(this));
这篇关于检测特定URL并更改活动的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!