簡體   English   中英

關閉活動時重新初始化片段

[英]Reinitialising Fragment when closing activity

我有一個帶有片段的活動,這個片段中有一個 map 和一些標記。 我在后台運行一項服務,更改標記的 position。

Each Marker has a boolean "isDrawn" and whenever the boolean is set to false the map is updated by adding drawing the marker ( I use LiveData to observe the markers) Whenever I close the Activity that contains the fragment I call onDestroyView, which sets isDrawn每個標記為假。 這樣,當我再次打開 Activity 時,標記會再繪制一次。 所有這一切都很好。

問題是這樣的:在片段中,我可以點擊標記,打開一個視圖,該視圖有一個打開另一個 Activity 的按鈕,當我關閉此 Activity(使用 BackButton)並且標記更改其 position(通過服務)時我在說Activity,我發現map上有兩個相同的標記。

知道我能做什么嗎? 我應該在關閉活動時刪除片段並重新創建它嗎? 那可能嗎? 如果是這樣,我應該如何進行?

在這里您可以嘗試 2 個選項

  1. 嘗試創建一個 static 變量並存儲一些標志值。
  2. 借助 isVisible() 或 getUserVisibleHint() 檢查 Fragment 是否可見

您必須使用此方法將標記添加到 map。

public final Marker addMarker (MarkerOptions options);

取一個Marker類型的變量並存儲它的引用,該引用由addMarker (MarkerOptions options);

喜歡

if(marker!=null){
 marker.remove(); //will clear the previous one, it might be null at first.
}  
marker=addMarker(yourOptions);//will add the latest one

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM