key1 无法解析为变量?

key1 cannot be resolved to a variable?

显然我的键值当前设置方式存在一些问题。目标是读取 Spinner 的值(使用字符串数组设置),然后基于它打开特定的本地 html 文件。

public class MainActivity extends Activity {

    private Button btnGo;

    String pageChoice;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        final Spinner page = (Spinner)findViewById(R.id.txtPage);
        final SharedPreferences sharedPref =PreferenceManager.getDefaultSharedPreferences(this);
        btnGo = (Button)findViewById(R.id.btnGo);
        btnGo.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                pageChoice = page.getSelectedItem().toString();

                //Hopefully will allow for "global" url setting.
                SharedPreferences.Editor editor = sharedPref.edit();
                editor.putString("key1", pageChoice);
                editor.commit();
                startActivity(new Intent(MainActivity.this, Web.class));
            }
        });
    }
}

错误位于我的Web.java。

public class Web extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        setContentView(R.layout.web);
        SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(this);
        String strPage = sharedPref.getString(key1, "");

        if (strPage = "By The Numbers") {
            //WebView
            WebView wv = (WebView) findViewById(R.id.webview1);
            WebSettings webSettings = wv.getSettings();
            webSettings.setBuiltInZoomControls(true);
            wv.loadUrl("file:///android_asset/2.html");
        } else if (strPage = "Photos") {
            //WebView
            WebView wv = (WebView) findViewById(R.id.webview1);
            WebSettings webSettings = wv.getSettings();
            webSettings.setBuiltInZoomControls(true);
            wv.loadUrl("file:///android_asset/3.html");
        }
    }

    @Override
    public void onBackPressed() {
        // TODO Auto-generated method stub
        super.onBackPressed();
    }
}

此外,我的 strPage 是字符串是否有问题?我如何将其更改为使用 If/Else 实例?

你必须在 key1 周围加上双引号

 String strPage = sharedPref.getString("key1", "");

因为它不是变量。它是一个字符串。

 String strPage = sharedPref.getString("key1", "");