android webview显示最后看到的页面

时间:2014-12-15 18:00:21

标签: android webview web

我创建了一个简单的webview应用程序并且工作正常,但每次打开应用程序时它都会显示主页面,而不是我上次使用的页面,就像常规浏览器一样

java文件:

public class MainActivity extends Activity {
WebView webView;

public static final String PREFS_NAME = "SharedPreferences";

public static final String PREF_STRING = "http://www.google.com";
  private SharedPreferences mPrefs;

/** Called when the activity is first created. */
 @Override
 public void onCreate(Bundle savedInstanceState) {
 super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_main);
  webView = (WebView) findViewById(R.id.webview);
// force web view to open inside application
 webView.setWebViewClient(new MyWebViewClient());
 openURL();

}

private void openURL() {
webView.loadUrl(PREF_STRING);


SharedPreferences settings = getSharedPreferences("StartPage", 0);
settings.getString("PREF_STRING", "http://www.google.com");
}


@Override
public void onResume() {

webView.loadUrl(mPrefs.getString(PREF_STRING, "http://www.google.com"));

}

private class MyWebViewClient extends WebViewClient {
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
}
}

xml文件

<RelativeLayout  
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:ads="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent">


<WebView
    android:id="@+id/webview"
    android:layout_width="match_parent"
    android:layout_height="match_parent" 
    android:layout_below="@id/progressbar_Horizontal"/>

 </RelativeLayout>

1 个答案:

答案 0 :(得分:3)

以下是如何保存上次访问过的网址的示例。

公共类WebViewActivity扩展了Activity {

private WebView webView;

public void onCreate(Bundle savedInstanceState){
    super.onCreate(savedInstanceState);
    setContentView(R.layout.webview_activity);

    //The web view
    webView = (WebView)findViewById(R.id.webViewEx1);
    webView.setWebViewClient(new MyWebClient());

    //Load the URL from saved url
    webView.loadUrl(getUrl());

}

public void saveUrl(String url){
    SharedPreferences sp = getSharedPreferences("SP_WEBVIEW_PREFS", MODE_PRIVATE);
    Editor editor = sp.edit();
    editor.putString("SAVED_URL", url);
    editor.commit();
}

public String getUrl(){

    SharedPreferences sp = getSharedPreferences("SP_WEBVIEW_PREFS", MODE_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");

}

private class MyWebClient extends WebViewClient {

    @Override
    public boolean shouldOverrideUrlLoading(WebView view, String url) {

        view.loadUrl(url);
        return true;

    }

    @Override
    public void onPageFinished(WebView view, String url) {
        super.onPageFinished(view, url);

        //Save the last visited URL
        saveUrl(url);
    }


}

}

基本上你所要做的就是将最后一个url保存在SharedPreferences中并从那里检索它。 希望它有所帮助。