在设备后退按钮上,将再次调用上一个片段 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 服务调用。我们在收件箱片段中实现了下拉刷新,这是下载任何新消息的事件。因此,我们在加载 MessageDetailsFragment 时采用一个标志 ON_BACK_PRESSED = 1,而在 InboxFragment 中,如果此标志设置为 1,则不要让 Web 服务调用 GetMessagesFromCloud()。

我们想知道上面是否是禁止 Web 服务调用的正确方法,因为当片段出现时总是调用 onCreateView。请指教。

据我们所知,当在iOS平台上完成相同的实现时,在回击时,视图中的片段会弹出,后面的片段会出现。每次回击时都不会进行 Web 服务调用,因为在 DidViewLoad 事件中调用 Web 服务。他们有 2 个事件 - DidViewLoad 和 DidViewAppear。因此,当他们回击时,DidViewAppear会在未进行服务调用的地方被调用,并且DidViewLoad不会被调用。

谢谢。

将响应存储在 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;
    }

最新更新