2012-04-01 69 views
0

在活動我喜歡加載的偏好:的Android在BaseAdapter類使用sharedpreferences

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

而且SharedPreferences sharedPreferences;被全球宣佈。

我有一個ExpandBaseAdapter類操作ExpandableListView。我想處理fontsizes在這個類,但它表明我

的方法getApplicationContext()是未定義的類型 ExpandBaseAdapter

錯誤。

我試圖添加sharedPreferences = context.getSharedPreferences("PREF_NAME", Context.MODE_PRIVATE); 但後來我只得到默認值。

如果我添加sharedPreferences = PreferenceManager.getDefaultSharedPreferences(ExpandBaseAdapter.this); 我得到

在類型的方法getDefaultSharedPreferences(上下文) PreferenceManager不適用於參數 (ExpandBaseAdapter)

我應該怎麼辦?

回答

2

當您在活動中創建此基礎適配器的實例時,您必須傳遞應用程序上下文。

並在基礎適配器構造器中聲明上下文爲屬性。

+1

沒有,聲明你的基礎轉接器在你的活動這樣的,BaseAdapter =新BaseAdapter相同(getApplicationContext());那麼在你的基礎適配器中使用全局變量Context mContext;那麼在基礎適配器的構造函數中使用mContext = context;然後在函數中使用mContext。 – 2012-04-01 21:13:40

+0

公平的解釋,但是,仍然沒有... – erdomester 2012-04-01 21:31:34

+0

是不可能發生的隊友,這是你可以通過上下文,嘗試解決,也許你失去了一些東西的唯一途徑。 – 2012-04-01 21:33:46

1

你必須使用YourActivity.this代替getApplicationContext(),無論是在一般情況下,特別是在你的適配器。

此致敬禮。

(下面編輯)

試試這個,然後:

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

,並使用mContext.getSharedPreferences()在你需要它。

+0

這不是一項活動。就像我說的,這是類ExpandBaseAdapter擴展BaseExpandableListAdapter – erdomester 2012-04-01 20:37:50

+0

很難把代碼中的註釋,所以我編輯我的答案 – pouzzler 2012-04-01 20:46:19

+0

這是我嘗試過,見上面 – erdomester 2012-04-01 21:06:36

0

傳遞一個Context對象爲LoadFontSize()作爲參數,並用它來獲取共享的首選項。

+0

你的意思是LoadFontSize(背景);和public void LoadFontSize(Context zContext){sharedPreferences = zContext.getSharedPreferences(「PREF_NAME」,Context.MODE_PRIVATE); loadedFontSize = sharedPreferences.getString(「fontsize」,「font1」); } ??仍然獲得默認值 – erdomester 2012-04-01 21:11:58