导航到不在当前活动中的片段

时间:2013-05-19 20:09:37

标签: android android-fragments android-animation

我使用here中的代码为较旧的Android设备创建翻转卡片动画。现在我想翻转到当前活动中不存在的片段。我试过这段代码:

MyFragment f = new MyFragment();

getActivity().getSupportFragmentManager().beginTransaction().add(R.id.item_detail_container, f).commit();
getActivity().getSupportFragmentManager().executePendingTransactions();

f.getView().setVisibility(View.GONE);
View root = getActivity().getWindow().getDecorView().findViewById(android.R.id.content);

FlipAnimation flipAnimation = new FlipAnimation(this.getView(), f.getView());
root.startAnimation(flipAnimation);

但接下来是FlipAnimation类中toView.setVisibility(View.VISIBLE);的NullPointerException。如何翻转到当前活动中没有的片段?

编辑:我用答案1及其评论来解决问题。此处的代码已更新,现在可以正常使用。

1 个答案:

答案 0 :(得分:2)

commit()上的

FragmentTransaction不是即时的。它是异步的。因此,在commit()返回时,您的片段尚未使用onCreateView()进行调用,因此getView()会返回null

我认为正确的答案是让您通过FragmentTransaction直接在setCustomAnimations()中应用动画。

除此之外,您可以尝试post()您的工作来执行FlipAnimation,因此它会在事务完成后发生。