[英]Call fragment method when AsyncTask finish on activity
我有一個帶有“導航抽屜活動”的應用程序,它在其上調用了一些片段。
在其中之一中,我具有Google Map集成,其中從SharedPreferences檢索,其中顯示了一些標記和內容。
在活動上,我有一個AsyncTask可以在單擊操作欄按鈕時更新數據。 它將新數據放入SharedPreferences中。
我在尋找一種方法來從FragmentMap再次調用paintmap()方法時遇到麻煩,FragmentMap是一種使用SharedPreferences數據並使用新標記繪制地圖的方法,依此類推。
我嘗試了OnSharedPreferenceChangeListener,但沒有結果。
還嘗試使用findFragmentByTag獲取實際片段,但無法調用該方法。
那么, 告訴片段數據已更新並且需要重繪地圖的更好方法是什么?
提前致謝。
編輯1:我嘗試過的一些事情:
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
final View view = inflater.inflate(R.layout.fragment_map, container, false);
txtUpdateInfo = (TextView) view.findViewById(R.id.last_update_info);
initilizeMap(); // This one includes paintMap at the end. It creates the map.
Check this pastebin for more: http://pastebin.com/DPPB7FiK
SharedPreferences.OnSharedPreferenceChangeListener spChanged = new SharedPreferences.OnSharedPreferenceChangeListener() {
@Override
public void onSharedPreferenceChanged(
SharedPreferences sharedPreferences, String key) {
paintMap();
}
};
return view;
}
還嘗試在MainActivity AsyncTask的postExecute上檢索該片段:
FragmentManager fm = getFragmentManager();
Fragment f = fm.findFragmentByTag("MAP");
f.paintMap(); // This gives me error and I cannot compile
另外,在同一位置:
FragmentMap f = new FragmentMap();
f.paintMap();
這最后一個編譯了,但是給了我NullPointer處理片段上的所有內容……都不起作用。
這段代碼的問題...
FragmentManager fm = getFragmentManager();
Fragment f = fm.findFragmentByTag("MAP");
f.paintMap(); // This gives me error and I cannot compile
...就是您已將f聲明為Fragment
,而Android Fragment
類沒有名為paintMap()
的方法。 您需要將其聲明為FragmentMap
findFragmentByTag
如下所示findFragmentByTag
的返回值...
FragmentManager fm = getFragmentManager();
FragmentMap f = (FragmentMap) fm.findFragmentByTag("MAP");
f.paintMap();
然后,對f.paintMap()
的調用應該起作用。
另外(僅供參考)以下內容將永遠無法使用...
FragmentMap f = new FragmentMap();
f.paintMap();
原因是,像Activity
一樣, Fragment
具有生命周期,這意味着直到將其用於FragmentTransaction
並經歷了其生命周期方法(例如onAttach
, onCreateView
, onResume
等) onAttach
,它才被完全初始化。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.