2016-01-20 44 views
0

叫我們有以下實現:在設備後退按鈕之前的片段Web服務調用再次

我們有一個片段例如爲:InboxFragment擁有的所有消息的列表視圖。

在InboxFrgament,負載我們調用Web服務使用Web服務調用來檢索來自雲的最新消息:

@Override 
public View onCreateView(LayoutInflater inflater, ViewGroup container, 
         Bundle savedInstanceState) { 
    // Inflate the layout for this fragment 
    view = inflater.inflate(R.layout.fragment_inbox, container, false); 
    context = getActivity(); 

    //Get Messages From Cloud - web service call 
    if (ON_BACK_PRESSED == 0) { 
     GetMessagesFromCloud(); 
    } 
} 

當您在信息挖掘,我們添加了一個新的片段MessageDetailsFragment到疊加。我們用下面的函數添加一個新的片段:

public void AddFragmentToStack(Fragment newFragment, String tag) { 
    FragmentTransaction ft = this.getSupportFragmentManager() 
      .beginTransaction(); 
    ft.replace(R.id.content_frame, newFragment, tag); 
    ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN); 
    ft.addToBackStack(null); 
    ft.commit(); 
} 

現在這個工作正常。但是當我們點擊設備返回按鈕時(當我們在MessageDetailsFragment上時),它將我們帶回到InboxFragment,並且onCreateView函數再次被調用,因爲Web服務調用來獲取新消息是由服務器決定的。

我們不希望每當我們回到MessageDetailsFragment時發生這個Web服務調用。我們有一個下拉菜單來實現InboxFragment,這是下載任何新消息的事件。所以,當MessageDetailsFragment被加載時,我們取得了一個標誌ON_BACK_PRESSED = 1,而在InboxFragment中,如果這個標誌被設置爲1,那麼不要讓web服務調用GetMessagesFromCloud()。

我們想知道如果上面是正確的方式來禁止Web服務調用,因爲片段出現時總是調用onCreateView。請指教。

根據我們的知識,當在iOS平臺上完成相同的實現時,在回擊時,視圖中的片段被彈出並出現後面的片段。由於在DidViewLoad事件中調用Web服務,因此每次當您回撥時都不會進行Web服務調用。他們有2個事件 - DidViewLoad和DidViewAppear。所以當他們回擊時,DidViewAppear被調用的地方沒有進行服務調用,並且DidViewLoad不會被調用。

謝謝。

回答

0

您將響應存儲在Object中並檢查其空值。

ResponseObject mResponse;//your response data type 

    @Override 
    public View onCreateView(LayoutInflater inflater, ViewGroup container, 
          Bundle savedInstanceState) { 
     // Inflate the layout for this fragment 
     view = inflater.inflate(R.layout.fragment_inbox, container, false); 
     context = getActivity(); 

     //Get Messages From Cloud - web service call 
     if (mResponse == null) { 
      GetMessagesFromCloud(); 
     } else { 
      //update UI 
     } 
    } 

    //your response callback. I am not sure what are your callbacks so its just a hint 
    public void onSucess(ResponseObject response) { 
     mResponse = response; 
    } 

Happy_Coding;

+0

謝謝。這是附加條件的另一種方式,只有在條件滿足時才進行Web服務調用。但是,有沒有更好的方式,Android本身提供(就像我在iOS的帖子中解釋的)? – user3663906