LayoutTransition导致Fragment在第二次创建时不显示

时间:2016-04-19 08:54:06

标签: android android-fragments android-activity android-transitions

我有一个实现此方法的活动:

public void pushFragment(MyFragment fragment) {
    stack.add(fragment);
    FragmentManager fragmentManager = getFragmentManager();
    FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
    fragmentTransaction.replace(R.id.main_frame_layout, fragment);
    fragmentTransaction.addToBackStack(null);
    fragmentTransaction.commit();
    setTitle(fragment.getTitle(this));
}

在一个片段中,我有一个带有这个onItemClickListener的列表视图:

getAppActivity().pushFragment(anotherFragment);

AnotherFragment onCreateView方法:

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

    setHasOptionsMenu(true);

    LayoutTransition t = new LayoutTransition();
    container.setLayoutTransition(t);

    View rootView = inflater.inflate(R.layout.another_layout, container, false);

    final ViewGroup vg = (ViewGroup)rootView.findViewById(R.id.avatar_image_layout);
    vg.getLayoutTransition().enableTransitionType(LayoutTransition.CHANGING);

    // Stuff

    return rootView;
}

在API级别> = 19一切正常。 在API 18和17上(我没有在API 16上进行测试),我第一次点击listview项目就可以了。然后我回去再点击该项目的另一次。这次创建片段,调用onActivityCreated和onCreateView等,但片段没有显示。

编辑1: 评论随机的东西,我发现问题是:

LayoutTransition t = new LayoutTransition();
container.setLayoutTransition(t);

评论这两行解决了这个问题,但我不知道为什么,我放松了动画......

1 个答案:

答案 0 :(得分:0)

这可能因API而异,但调用FragmentTransactioninfo)后,commit()可能无法立即应用。

根据 FragmentTransaction.java commit()方法声明:

 * Schedules a commit of this transaction.  The commit does
 * not happen immediately; it will be scheduled as work on the main thread
 * to be done the next time that thread is ready.

为了立即实现这一点,在commit()方法之后,我们调用 FragmentManager.java ' s executePendingTransactions()more info):

 * After a {@link FragmentTransaction} is committed with
 * {@link FragmentTransaction#commit FragmentTransaction.commit()}, it
 * is scheduled to be executed asynchronously on the process's main thread.
 * If you want to immediately executing any such pending operations, you
 * can call this function (only from the main thread) to do so.  Note that
 * all callbacks and other related behavior will be done from within this
 * call, so be careful about where this is called from.
相关问题