【问题标题】:Visit Last Loaded URL访问上次加载的 URL
【发布时间】:2017-10-20 08:24:34
【问题描述】:

我正在 Xamarin android 中制作用户导航的应用。该应用程序包含 web 视图。当用户打开 webview 时,会加载 url 并可以完成浏览。当他结束应用程序并再次打开它时,会再次加载 URL,而不是查看上次访问的 URL。

我不知道我在这里做错了什么。

    protected override void OnCreate(Bundle savedInstanceState)
    {
        base.OnCreate(savedInstanceState);

        // Set our view from the "main" layout resource
        SetContentView(Resource.Layout.Main);
        webView = FindViewById<WebView>(Resource.Id.webView1);
        webView.SetWebViewClient(new MyWebClient());
        CookieManager.Instance.SetAcceptCookie(true);
        webView.Settings.JavaScriptEnabled = true;
        webView.Settings.SetAppCacheEnabled(true);
        webView.LoadUrl(getUrl());
        webView.SetPadding(0, 0, 0, 0);


        webView.Settings.SetSupportZoom(true);

    }
    public void saveUrl(String url)
    {
        ISharedPreferences sp = GetSharedPreferences("SP_WEBVIEW_PREFS", FileCreationMode.Private);
        ISharedPreferencesEditor editor = sp.Edit();
        editor.PutString("SAVED_URL", url);
        editor.Commit();
    }
    public String getUrl()
    {

        ISharedPreferences sp = GetSharedPreferences("SP_WEBVIEW_PREFS", FileCreationMode.Private);
        //If you haven't saved the url before, the default value will be google's page
        return sp.GetString("SAVED_URL", "http://google.com");

    }
    public void onPageFinished(WebView view, String url)
    {
        this.onPageFinished(view, url);
        saveUrl(url);

    }
}

internal class MyWebClient : WebViewClient
{
    public override bool ShouldOverrideUrlLoading(WebView view, string url)
    {
        view.LoadUrl(url);
        return false;
    }
}

【问题讨论】:

  • 你需要写一个正确的标题,并解决这个问题,什么是“再次加载URL” - 你的意思是从头开始?
  • 是的,从头开始

标签: webview xamarin.android android-webview


【解决方案1】:

您已将onPageFinished 方法放在一个活动中。它应该在MyWebClient 类中被覆盖,如下所示:

internal class MyWebClient : WebViewClient 
{ 
     public override bool ShouldOverrideUrlLoading(WebView view, string url) 
     { 
           view.LoadUrl(url); 
           return false; 
     } 


     public override void OnPageFinished(WebView view, String url) 
     { 
           base.OnPageFinished(view, url); 

           //Save the url here. 
           //This method itself gives you the last url loaded as it's url Parameter.
           ISharedPreferences sp = Application.Context.GetSharedPreferences("SP_WEBVIEW_PREFS", FileCreationMode.Private);
           ISharedPreferencesEditor editor = sp.Edit();
           editor.PutString("SAVED_URL", url);
           editor.Commit().
     }
}

URL 加载完成后会自动调用此方法,然后您会将加载的 URL 存储在此方法中。

【讨论】:

  • 我认为您不应该使用在您的活动中编写的 saveUrl 方法。您最好将其代码移动到 OnPageFinished 方法本身并从那里保存最后一个 url。如果您愿意,可以使用 webView.Url,但这将作为 OnPageFinished 方法参数的一部分给出。最好从活动中删除 saveUrl 方法并检查我编辑的答案。
猜你喜欢
  • 2013-08-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-12-24
  • 1970-01-01
  • 1970-01-01
  • 2015-03-10
  • 2016-11-12
相关资源
最近更新 更多