2017-10-12 66 views
1

我使用SharedPreferences來存儲和片段發送數據到其他4個片段,但我的問題是應用程序正在運行的時候,我就派單擊按鈕數據它需要其他片段的某個時間來實際接收數據(或者在刷新3或4次後刷新頁面時)我已嘗試在每個片段中嘗試setUserVisibleHint,並且在活動中嘗試了onpagechangelistener,但沒有任何更改。當我滑動頁面或按下按鈕時,如何讓其他片段接收數據?力(PagerAdapter片段片段)發送使用SharedPreferences數據

note:我不想在每個片段中加載按鈕來加載數據。

發件人:

int riddle; 
    Context context = getActivity(); 
    SharedPreferences SU = context.getSharedPreferences(
         "Riddle", Context.MODE_PRIVATE); 
    SharedPreferences.Editor editor= SU.edit(); 
    editor.putString("Riddle",""+riddle); 
    editor.commit(); 

其他片段:

 int Riddle; 
     Context context = getActivity(); 
     SharedPreferences SU = context.getSharedPreferences(
       "Riddle", Context.MODE_PRIVATE); 
     Riddle= Integer.parseInt(SU.getString("riddle","")); 

UPDATE 我提出在原崗位犯錯時,發送方應該是:

int riddle; 
    Context context = getActivity(); 
    SharedPreferences SU = context.getSharedPreferences(
         "Riddle", Context.MODE_PRIVATE); 
    SharedPreferences.Editor editor= SU.edit(); 
    editor.putString("riddle",""+riddle); 
    editor.commit(); 

因爲關鍵的東西。

還有一個問題,片段im發送數據是最後一頁(第5頁),當我發送數據時,它旁邊的頁面(第4頁)不會更新,直到我滑動到第3頁並返回爲從SharedPreferences這是在發件人使用了獲取數據它

+0

相反上下文語境= getActivity(),您可以使用片段的getContext的()對? – Anonymous

+0

@匿名讓我試試1秒 – amirsoltani

+0

@匿名是的,你可以 – amirsoltani

回答

1

使用本

Riddle= Integer.parseInt(SU.getString("Riddle","")); 

,而不是這個

Riddle= Integer.parseInt(SU.getString("riddle","")); 
+0

爲感謝你指出來,還是一個問題,旁邊的「發件人」頁面的頁面重新加載犯規 – amirsoltani

+0

@amirsoltani你能解釋更多 –

+0

是我使用viewpager所以片段從IM發送的數據是最後一頁(第5頁)當我發送數據時,發送數據的頁面(頁面4)旁邊的頁面不會更新,直到我滑動到頁面3並返回到它 – amirsoltani

2

使用相同的密鑰。變化:

Riddle= Integer.parseInt(SU.getString("riddle","")); 
             ^^^^^ 

Riddle= Integer.parseInt(SU.getString("Riddle","")); 
+0

哦,是啊對不起,這是一個錯誤,謝謝你指出來,還是一個問題,旁邊的「發件人」頁面的頁面重新加載犯規對不起 – amirsoltani