[英]Android using sharedpreferences in BaseAdapter class
在活動中,我加載如下首選項:
public void LoadFontSize(){
sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
loadedFontSize = sharedPreferences.getString("fontsize", "font3");
}
和SharedPreferences sharedPreferences; 是全局聲明的。
我有一個ExpandBaseAdapter類,用於操作ExpandableListView。 我想在此類中處理字體大小,但它告訴我
對於類型ExpandBaseAdapter,未定義方法getApplicationContext()
錯誤。
我試圖添加sharedPreferences = context.getSharedPreferences("PREF_NAME", Context.MODE_PRIVATE);
但是然后我只得到默認值。
如果我添加sharedPreferences = PreferenceManager.getDefaultSharedPreferences(ExpandBaseAdapter.this);
我懂了
PreferenceManager類型的方法getDefaultSharedPreferences(Context)不適用於參數(ExpandBaseAdapter)
我該怎么辦?
在活動中創建此基本適配器的實例時,必須傳遞應用程序上下文。
並在基礎適配器構造器中將上下文聲明為屬性。
通常,尤其是在您的適配器中,必須使用YourActivity.this代替getApplicationContext()。
最好的祝福。
(在下面編輯)
然后嘗試以下方法:
class ExpandBaseAdapter {
Context mContext;
void ExpandBaseAdapter(Context context) {
mContext = context;
}
}
並在需要的地方使用mContext.getSharedPreferences()。
將Context對象作為參數傳遞給LoadFontSize()
,並使用該對象獲取共享的首選項。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.