In my projects I have several screen(Fragments) and I want to give animation to the fragments elements(views). I have used view pager and viewpager adapter and fragments. The ma
Overriding setUserVisibleHint() in each of my pages/fragments worked for me. You can simply call view.startAnimation(animation) inside your setUserVisibleHint(). However, there is one problem with this approach:
In fragments,
setUserVisibleHint()gets called beforeonCreateView()andonViewCreated.
The implication of this is that when the fragment starts for the first time and you call view.startAnimation(animation) inside setUserVisibleHint(), view and animation would both be null and the app would crash.
How then can you fix this problem?
In each of your pages/fragments, simply declare a global boolean (let's call it fresh_load), use this boolean to check whether the fragment is being loaded for the first time. Here's an illustration:
boolean fresh_load = true;
Animation move;
ImageView car;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_carousel_two, container, false);
// init move and car variables
if(fresh_load) {
car.startAnimation(animation);
fresh_load = false;
}
return view;
}
@Override
public void setUserVisibleHint(boolean isVisibleToUser) {
super.setUserVisibleHint(isVisibleToUser);
if((isVisible() && animation != null) && !fresh_load) {
car.startAnimation(move);
}
}
I hope this helps. Merry coding!