片段转换的问题

时间:2016-08-17 12:07:33

标签: java android android-fragments android-transitions fragmenttransaction

我在一个活动中有两个片段,我希望第一个片段优雅地从屏幕左侧滑出视图,而第二个片段通过屏幕右侧进入。我正在使用Transitions API,这就是:

初始屏幕:

Initial screen

过渡发生得很糟糕:

Transition occurs poorly

我的代码如下:

HomeFragment savedHomeFragment = (HomeFragment) getSupportFragmentManager().findFragmentByTag(HOME_FRAGMENT);

    if (savedHomeFragment == null) {
        mHomeFragment = new HomeFragment();
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            mHomeFragment.setEnterTransition(new Fade(Fade.MODE_IN));
            mHomeFragment.setExitTransition(new Slide(Gravity.START));
        }
        FragmentManager fragmentManager = getSupportFragmentManager();
        FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
        fragmentTransaction.add(R.id.placeholder, mHomeFragment, HOME_FRAGMENT);
        fragmentTransaction.commit();
    } else {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            savedHomeFragment.setEnterTransition(new Fade(Fade.MODE_IN));
            savedHomeFragment.setExitTransition(new Slide(Gravity.START));
        }
    }

void buttonClick() {
    TargetFragment targetFragment = new TargetFragment();
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
        targetFragment.setEnterTransition(new Slide(Gravity.END));
    }
    FragmentManager fragmentManager = getSupportFragmentManager();
    FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
    fragmentTransaction.replace(R.id.placeholder, targetFragment , TARGET_FRAGMENT);
    fragmentTransaction.addToBackStack(null);
    fragmentTransaction.commit();
}

我做错了什么?

1 个答案:

答案 0 :(得分:1)

第一个片段上的按钮放在没有背景的容器上。您看到的白色背景是您的活动的背景。在Fragment1布局的根元素上提供背景颜色,您的问题将得到解决。