等到片段已添加到UI

Pha*_*tom 6 multithreading android android-fragments

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

任何更好的做法(例子)然后是下面的代码(比如等到第一个片段被连接,而且在某个时间间隔没有)?:

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();
Run Code Online (Sandbox Code Playgroud)

非常感激.

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

@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();
Run Code Online (Sandbox Code Playgroud)

Car*_*s J 8

片段生命周期对您有利.根据文档,onStart()方法是"当片段对用户可见时调用",所以我建议你在你的第一个片段类中做这样的事情:

public void onStart() {

    super.onStart();
    ((MainActivity)getActivity()).loadSecondFragment();
}
Run Code Online (Sandbox Code Playgroud)

在您的活动中:

public void loadSecondFragment() {
    if (isLandscape) {
        openSecondFragment(mIndex, R.id.rightConent);
    }    
}
Run Code Online (Sandbox Code Playgroud)

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