2014-12-04 49 views
0

我有一個由我的自定義類填充的listview。讓listview sharedPreference知道

我不確定最好的方法是如何使sharedPreferences和Listview設置的偏好之間的關係。

理想情況下,我想添加一個「showMe」類型成員到類,然後在自定義適配器的listview,我可以簡單地檢查該標誌之前,我讓適配器添加它。 但問題是,一旦首選項被設置,我應該在哪裏設置這個標誌?我知道我在SettingsActivity中有onSharedPreferenceChanged(),但是如何引用列表以從SettingsActivity中獲取我的客戶類標誌?

即使是最好和最有效的方法嗎?

我也考慮過在MainActivity的onResume中這麼做 - 因爲它在您從SettingsActivity返回時調用,並且至少在MainActivity中我可以訪問List。但我只是不確定該邏輯是否正確,因爲我嘗試了它,出於某種原因,列表對象無法訪問onResume(應用程序崩潰)。

所以我在如何讓我的列表視圖知道偏好更改的最佳做法,以便根據每個項目是否應顯示刷新自己。

+0

嘿馬卡帕卡,這是否解決您的問題?如果是的話,你也可以贊成答案。 :) – Naveen 2014-12-04 16:06:25

回答

0

你有沒有嘗試localbroadcasting,在onSharedPreferenceChanged()?

在活動中添加一個接收器,以便在改變喜好時,通過意圖傳遞數據並在廣播接收器中接收該數據並刷新列表。

在你的活動:

private BroadcastReceiver statusReceiver = new BroadcastReceiver() 
    { 
    public void onReceive(Context context,Intent intent) 
     { 
      //get data from intent 
     //use intent.getExtras().get(name); 
     }; 
    }; 

註冊中的onResume的意圖()活動爲:

LocalBroadcastManager.getInstance(this) 
         .registerReceiver(statusReceiver, 
              new IntentFilter("updateList")); 

而且在onPause()刪除監聽,所以你要確保,當活動在後臺,聽衆是未註冊的。

LocalBroadcastManager.getInstance(this) 
         .unregisterReceiver(statusReceiver); 

並從onSharedPreferenceChanged();

Intent intent = new Intent("updateList"); 
intent.putExtra(name, value) 
LocalBroadcastManager.getInstance(this).sendBroadcast(intent); 
相關問題