2016-03-08 62 views
2

我正在更新當前顯示的視圖並隱藏/顯示兩個片段。確定哪個片段顯示要更新

FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction(); 

    if (mTaxLocationListViewFrag.isVisible()) { 
     if (mGoogleMapFrag == null) { 
      mGoogleMapFrag = new GoogleMapFragment(); 
      fragmentTransaction.add(R.id.fragment_container, mGoogleMapFrag); 
     } 
     fragmentTransaction.hide(mListViewFrag); 
     fragmentTransaction.show(mGoogleMapFrag).commit(); 

    } else {fragmentTransaction.hide(mGoogleMapFrag).show(mListViewFrag).commit(); 
    } 

    updateDisplay(); 

updateDisplay方法 -

if (mListViewFrag != null && mListViewFrag.isVisible()) { 
      Log.d(TAG, "Update Location ListView"); 
      mListViewFrag.setLocations(mLocations); 
     } 

     if (mGoogleMapFrag != null && mGoogleMapFrag.isVisible()) { 
      Log.d(TAG, "Update Google Maps Markers"); 
      //Convert locations to markers to display. 

     } 

的問題是我猜fragmentTransaction執行.show.hide時是異步的,因爲它認爲被隱藏仍呈現片段updateDisplay不能正常工作。有沒有更可靠的方法來檢查哪個片段要更新?

+1

嘗試在添加片段後添加fragmentTransaction.executePendingTransactions()。 – Piyush

+0

@Piyush似乎已經做到了。如果你想添加爲解決方案。我會很樂意接受它。 – Alan

回答

1

在添加片段後添加fragmentTransaction.executePendingTransactions()。來自executePendingTransactions()的文檔:

它計劃在進程的主線程上異步執行。 如果您想立即執行任何此類未決操作,您可以調用此函數(僅限於主線程)來執行此操作。請注意, 所有回調和其他相關行爲都將在此 調用中完成,因此請注意從何處調用此函數。