Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android ViewPager CrossFade animation

I implement a BottomNavigation view for android and I have some fragments to show as BottomNavigation pages. According to the Google Material Design Guide Lines I want to show fragments with cross fade animation.

By touching BottomNavigation's items my ViewpPager change the fragments with default slide animation.

I read some solutions in this and this. but these aren't really fade animation and I couldn't set fading duration.

So is there any way to set an animation on changing ViewPager's tabs ?

like image 940
FarshidABZ Avatar asked Oct 05 '16 21:10

FarshidABZ


2 Answers

Finally, I found my answer.

I changed the ViewPager with a layout to keeps my fragments(a frame layout). Then I added fragments into a fragmentTransaction.

By touching an item on BottomNavigation, current fragment hides and new fragments goes to shown with a fade animation defined in fragmentTransaction.

and this is my code:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main_page);

    addFragmentsToManager();
}

private void addFragmentsToManager() {
    FragmentManager fragmentManager = getSupportFragmentManager();
    FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
    fragmentTransaction.setCustomAnimations(R.anim.fade_in, R.anim.fade_out);

    fragmentTransaction.add(R.id.flContent, tripFragment, tripFragment.getClass().getSimpleName());
    fragmentTransaction.add(R.id.flContent, notificationFragment, notificationFragment.getClass().getSimpleName());
    fragmentTransaction.add(R.id.flContent, searchFragment, searchFragment.getClass().getSimpleName());
    fragmentTransaction.add(R.id.flContent, profileFragment, profileFragment.getClass().getSimpleName());

    fragmentTransaction.hide(tripFragment);
    fragmentTransaction.hide(notificationFragment);
    fragmentTransaction.hide(searchFragment);
    fragmentTransaction.hide(profileFragment);
    fragmentTransaction.commit();
}

private void changeTab(int position) {
    Fragment fragment;
    switch (position) {
        fragment = .....// get framgnet from position
    }

    FragmentManager fragmentManager = getSupportFragmentManager();
    FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction(); 
    fragmentTransaction.setCustomAnimations(R.anim.fade_in, R.anim.fade_out);

    fragmentTransaction.hide(prvFragment);
    fragmentTransaction.show(fragment).commit();
    prvFragment = fragment;
}
like image 140
FarshidABZ Avatar answered Nov 15 '22 00:11

FarshidABZ


There is a problem with adding and hiding fragments.

When the application is idle and the phone goes to sleep mode if you turn back to the application all fragments shown in activity and you see all layouts in one.

like image 43
Abr Sefid Avatar answered Nov 15 '22 00:11

Abr Sefid