3

我有一个扩展 SurfaceView 的 GamePanel 类,所以我不能为 SharedPreferences 扩展 Activity。如何在不扩展类的情况下使用 getSharedPreferences?

我已经尝试过:

SharedPreferences sp = Activity.getSharedPreferences("MyScore", Context.MODE_PRIVATE);

但是,我收到一条错误消息,提示“无法从静态上下文中引用。

4

1 回答 1

2

您可以将 Application 类中的 Sharedpreferences 初始化为静态变量,然后在每个非活动类中使用它:

public class MyApplication extends Application {

    private static SharedPreferences sharedPreferences;

    public static SharedPreferences getSharedPreferences() {
        return sharedPreferences;
    }

    public void setSharedPreferences(SharedPreferences sharedPreferences) {
        this.sharedPreferences = sharedPreferences;
    }

    @Override
    public void onCreate() {
        super.onCreate();

        setSharedPreferences(MyApplication.this
            .getSharedPreferences("MyScore",getApplicationContext().MODE_PRIVATE));

现在,每当您想在静态上下文中访问 sharedprefs 时,您始终可以像这样使用它:

    String value = MyApplication.getSharedPreferences().getString("key","");
于 2016-11-10T06:37:00.420 回答