等到片段被添加到 UI

Wait until fragment has been added to the UI

在我的应用程序中,在横向模式下,我需要附加两个片段。为了做到这一点,第二个片段需要等到第一个片段被附加(添加),然后才被添加。原因是第一个片段需要执行第二个片段需要的功能。我设法通过一个线程做到了这一点,但在这种情况下,它只等待指示的时间量,然后再附加第二个片段,如果第一个片段没有在给定的时间内附加,应用程序将崩溃,因为第二个片段没有必要的数据。

比下面的代码有更好的做法(示例)吗(比如等到第一个片段被附加,而不是在某个时间间隔)? :

getSupportFragmentManager()
                .beginTransaction()
                .replace(R.id.mainContent, fragment).commit();
        Thread thread = new Thread() {
            @Override
            public void run() {
                try {
                    synchronized (this) {
                        wait(1000);
                    }
                } catch (InterruptedException e) {

                }
                if (isLandscape) {
                openSecondFragment(mIndex, R.id.rightConent);
                }
            }
        };
        thread.start();

非常感谢。

我需要在第一个片段中执行的处理程序:

@SuppressLint("HandlerLeak")
protected void loadAccountList() {

    LoadAccountList loadAccountListThread = new LoadAccountList(new Handler() {

        @SuppressWarnings("unchecked")
        public void handleMessage(Message msg) {
            switch (msg.what) {
            case LOAD_SUCCESSFUL_CODE:
                items = (ArrayList<Account>) msg.obj;
                break;
            case LOAD_FAILED_IOEXCEPTION_CODE:
                getActivity().showDialog(ERROR_DIALOG);
                break;
            default:
                break;
            }
        }
    });
    loadAccountListThread.start();

创建 Fragment 时调用 onCreateView

public static class CustomFragment extends SupportMapFragment{

        public CustomFragment() {}

        @Override
        public View onCreateView(LayoutInflater arg0, ViewGroup arg1, Bundle arg2) {
            return super.onCreateView(arg0, arg1, arg2);

        }
}

Fragments 生命周期在这里对您有利。根据文档,方法 onStart() 是 "Called when the Fragment is visible to the user",因此我建议您在第一个片段 class:

中执行类似的操作
public void onStart() {

    super.onStart();
    ((MainActivity)getActivity()).loadSecondFragment();
}

在你的 Activity 中:

public void loadSecondFragment() {
    if (isLandscape) {
        openSecondFragment(mIndex, R.id.rightConent);
    }    
}

瞧!尝试任何一种生命周期方法,看看哪种方法最适合您的目的。

首先 @SuppressLint("HandlerLeak") 不好。如果你不注意泄漏,你的内存就会被填满。

我的方案(个人喜好)

我喜欢使用 Otto 传递消息,同时仍然保持松耦合。 它允许您设置一个 EventBus,不同的 classes 可以简单地注册并接收他们想要的事件。 在这种情况下,您可以制作一个助手 class 来加载数据并在收到数据(或错误)时触发一个事件。 然后你在你的第二个片段中捕捉到它并填充你的列表。 (同时你可以显示一个不确定的进度条或其他东西)

这样,您就不必在加载片段之前等待接收到数据。

您可以在此处找到文档:https://github.com/square/otto

您可以通过注册FragmentLifecycleCallbacks来观察Fragments的创建 在 FragmentManager.

实现您感兴趣的回调,例如 onFragmentAttached, onFragmentResumed