【问题标题】:Access Android sharedPreferences from surfaceview从surfaceview访问Android sharedPreferences
【发布时间】:2012-05-31 23:02:05
【问题描述】:

访问 sharedpreferences 的代码是

SharedPreferences settings = getSharedPreferences("MySettings", 0);
    float X = settings.getFloat("myFloat", 0);

但是这只能在活动中起作用。

我如何从其他地方访问它?

单身是个好主意吗?我将如何设置和访问这个单例。

我只想存储 4 个浮点数,这会很棒!但没有什么是直截了当的:(

【问题讨论】:

    标签: android android-activity sharedpreferences


    【解决方案1】:

    SurfaceView 没有 getContext() 方法吗?

    getContext().getSharedPreference();
    

    如果这不起作用,您可以在启动时将这些变量加载到单例中,因为其中只有 4 个。

    public class ClassicSingleton {
    
       public float float1;
       public float float2;
       public float float3;
       public float float4;
    
       private static ClassicSingleton instance = null;
       protected ClassicSingleton() {
          // Exists only to defeat instantiation.
       }
       public static ClassicSingleton getInstance() {
          if(instance == null) {
             instance = new ClassicSingleton();
          }
          return instance;
       }
    }
    

    【讨论】:

    • 是的,你的权利。我通过构造函数方法传入了上下文。所以它实际上只是context.getSharedPreference(); 谢谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-11-19
    • 1970-01-01
    • 2020-01-20
    • 2014-09-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多