我还在学习Java。我正在尝试使用SharedPreferences在我的WebView中设置url,以便我可以设置下次启动应用时显示的页面。 并尝试使用菜单设置/更改值。
以下是我到目前为止:
public class test extends Activity {
public static final String PREFS_NAME = "SharedPreferences";
public static final String PREF_STRING = "http://www.google.com";
private SharedPreferences mPrefs;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mPrefs = getSharedPreferences(PREFS_NAME, 0);
webview = new WebView(this) {
};
webChromeClient = new WebChromeClient() {
};
webview.setWebChromeClient(webChromeClient);
webview.setWebViewClient(webViewClient);
setContentView(webview);
/** Load the Browser Settings */
webview.loadUrl(PREF_STRING);
SharedPreferences settings = getSharedPreferences("StartPage", 0);
settings.getString("PREF_STRING", "http://www.google.com");
}
/** Begin Globals */
public WebView webview;
public WebChromeClient webChromeClient;
public WebViewClient webViewClient;
/*** define menu options */
private static final int MENU_PAGE1 = 1;
private static final int MENU_PAGE2 = 2;
/*** menu items */
public boolean onCreateOptionsMenu(Menu menu) {
menu.add(0, MENU_PAGE1, 0, "Set page 1 to show when app is started");
menu.add(0, MENU_PAGE2, 0, "Set page 2 to show when app is started");
return true;
}
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case MENU_PAGE1:
Editor e = mPrefs.edit();
e.putString(PREF_STRING, "http://www.yahoo.com");
e.commit();
Toast.makeText(this, "Page 1 is set!", Toast.LENGTH_SHORT).show();
return true;
}
switch (item.getItemId()) {
case MENU_PAGE2:
Editor e = mPrefs.edit();
e.putString(PREF_STRING, "http://www.ask.com");
e.commit();
Toast.makeText(this, "Page 2 is set!", Toast.LENGTH_SHORT).show();
return true;
}
return false;
}
}
如此接近,到目前为止......任何提示或想法?
答案 0 :(得分:1)
Try this:
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
mPrefs = getSharedPreferences(PREFS_NAME, 0);
webview = new WebView(this) {
};
webChromeClient = new WebChromeClient() {
};
webview.setWebChromeClient(webChromeClient);
webview.setWebViewClient(webViewClient);
setContentView(webview);
/* Load the last saved preference. */
webview.loadUrl(mPrefs.getString(PREF_STRING, "http://www.google.com"));
}