【问题标题】:Android using sharedpreferences in BaseAdapter classAndroid 在 BaseAdapter 类中使用 sharedpreferences
【发布时间】:2012-04-01 20:09:32
【问题描述】:

在活动中我加载首选项,例如:

   public void LoadFontSize(){
        sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
        loadedFontSize = sharedPreferences.getString("fontsize", "font3");
      }

和 SharedPreferences sharedPreferences;是全局声明的。

我有一个运行 ExpandableListView 的 ExpandBaseAdapter 类。我想在这个类中处理字体大小,但它显示了我

该类型的方法 getApplicationContext() 未定义 展开BaseAdapter

错误。

我尝试添加sharedPreferences = context.getSharedPreferences("PREF_NAME", Context.MODE_PRIVATE); 但后来我只得到默认值。

如果我添加sharedPreferences = PreferenceManager.getDefaultSharedPreferences(ExpandBaseAdapter.this); 我明白了

类型中的getDefaultSharedPreferences(Context)方法 PreferenceManager 不适用于参数 (ExpandBaseAdapter)

我该怎么办?

【问题讨论】:

    标签: android sharedpreferences


    【解决方案1】:

    当您在 Activity 中创建此基本适配器的实例时,您必须传递应用程序上下文。

    并将上下文声明为基本适配器构造函数中的属性。

    【讨论】:

    • 不,像这样在您的活动中声明您的基本适配器,BaseAdapter = new BaseAdapter(getApplicationContext());然后在您的基本适配器中使用全局变量 Context mContext;然后在基本适配器的构造函数中使用 mContext = context;然后在你的函数中使用 mContext。
    • 不可能发生,伙计,这是你传递上下文的唯一方法,尝试解决,也许你错过了什么。
    • 顺便问一下,你有没有为 sharedpreferences 设置另一个值,所以你没有得到默认值??
    • 后来我突然想到,我并没有完全按照你告诉我的去做。我将该适配器类保存在一个单独的 java 文件中。然后我把它放在活动中,它就可以工作了!谢谢
    【解决方案2】:

    您必须使用 YourActivity.this 而不是 getApplicationContext(),一般来说,尤其是在您的适配器中。

    最好的问候。

    (在下面编辑)

    然后试试这个:

    class ExpandBaseAdapter {
      Context mContext;
      void ExpandBaseAdapter(Context context) {
        mContext = context;
      }
    }
    

    并在需要的地方使用 mContext.getSharedPreferences()。

    【讨论】:

    • 这不是一项活动。就像我说的,这是类 ExpandBaseAdapter 扩展 BaseExpandableListAdapter
    【解决方案3】:

    将一个上下文对象作为参数传递给LoadFontSize(),并使用它来获取共享首选项。

    【讨论】:

    • 你的意思是 LoadFontSize(context);和 public void LoadFontSize(Context zContext){ sharedPreferences = zContext.getSharedPreferences("PREF_NAME", Context.MODE_PRIVATE); loadFontSize = sharedPreferences.getString("fontsize", "font1"); ??仍然获得默认值
    猜你喜欢
    • 1970-01-01
    • 2011-11-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-01-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多