ListView animate single item - android

I got a ListView with items in it.
When the user clicks an item it's height should scale to zero and all items below should scroll up.
My code below doesnt work.
With my code the item which was clicked scales right, but the items below dont scroll up, they stay at the same position.
I've also tried it with an LinearLayout but there is the same problem.
There is an app which does this right. It's called Tasks.
My current implementation looks like this:
#Override
public void onItemClick(AdapterView<?> arg0, View v, final int index,
long id) {
Animation anim = AnimationUtils.loadAnimation(getActivity(),
R.anim.scaleup);
v.startAnimation(anim);
}
<set android:shareInterpolator="false" >
<scale
android:duration="700"
android:fillAfter="false"
android:fillBefore="false"
android:fromXScale="1.0"
android:fromYScale="1.0"
android:interpolator="#android:anim/accelerate_decelerate_interpolator"
android:pivotY="0%"
android:toXScale="1.0"
android:toYScale="0.0" />
</set>

Here's a class I made (modified from source I found here) that may give you the functionality you want.
public class FadeUpAnimation extends Animation {
int mFromHeight;
View mView;
public FadeUpAnimation(View view) {
this.mView = view;
this.mFromHeight = view.getHeight();
}
#Override
protected void applyTransformation(float interpolatedTime, Transformation t) {
int newHeight;
newHeight = (int) (mFromHeight * (1 - interpolatedTime));
mView.getLayoutParams().height = newHeight;
mView.setAlpha(1 - interpolatedTime);
mView.requestLayout();
}
#Override
public void initialize(int width, int height, int parentWidth,
int parentHeight) {
super.initialize(width, height, parentWidth, parentHeight);
}
#Override
public boolean willChangeBounds() {
return true;
}
}
Then this is how I'm using it
View tv = ...
Animation a = new FadeUpAnimation(tv);
a.setInterpolator(new AccelerateInterpolator());
a.setDuration(300);
tv.setAnimation(a);
tv.startAnimation(a);
You can play with it to see if you can get it to fit your needs.

Will you use the clicked item again? If not, then you could
Wait until the animation finishes
Delete the item from wherever you store the underlaying data
Then call the notifyDataSetChanged() method of your listadapter

The Android don't act like HTML, when you change the width, height or visibility in a view, the other views don't update theirs positions.
If you need to do that, you must update all the listview and your views inside, individually. This is a complex code to do.

Related

Android - Expand view's height and width

I am using a RelativeLayout in my android studio project and I want it to expand both sides (height and width) simultaneously. I have the initial height (0dp) and final height (130dp), initial width(0dp) and final width (250dp). I have copied a code for expanding its height from 0dp - 130dp and its working fine. I just want to know how can I modify it to consider the width parameters also.
Here is my code for expanding height. I have used ValueAnimator for the task.
MainActivity.java
public static void expand(final View v, int duration, int targetHeight, int targetWidth){
v.setVisibility(View.VISIBLE);
ValueAnimator valueAnimator = ValueAnimator.ofInt(0, targetHeight);
valueAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
#Override
public void onAnimationUpdate(ValueAnimator animation) {
v.getLayoutParams().height = (int) animation.getAnimatedValue();
v.requestLayout();
}
});
valueAnimator.setInterpolator(new DecelerateInterpolator());
valueAnimator.setDuration(duration);
valueAnimator.start();
}
And I am calling this method from onClickListener for the button like this:
ib.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//cv.setVisibility(View.VISIBLE);
int height = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 130, getResources().getDisplayMetrics());
int width = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 250, getResources().getDisplayMetrics());
expand(cv, 100, height, width);
}
});
`
where cv is my RelativeLayout whose height and width I want to expand.
Thanks.
I will suggest you to use a more simple approach for animation ,using animation and animation utils class such as following
Create a new directory under res such following
right click on res->new->android resource directory->then select resource type as anim(you can change directory name also,do not change anything else).
Then create a new xml file(i have zoom_in.xml) under that newly created directory and put below code in it,
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">
<scale
android:fromXScale="0dp"
android:fromYScale="0dp"
android:pivotX="50%"
android:pivotY="50%"
android:duration="4000"
android:toXScale="250dp"
android:toYScale="130dp"
>
</scale>
</set>
Then in button click event use the animation as following,
ib.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Animation a1=AnimationUtils.loadAnimation(getApplicationContext(),R.anim.zoom_in);//here zoom_in.xml is placed inside res/anim(i have anim name ,you can have yours)/zoom_in
cv.startAnimation(a1);
}
});
for more information go to https://www.journaldev.com/9481/android-animation-example

Custom Property animation not working on disabling animation

I am creating an android application where each fragment is bind to a custom left to right slide animation. That i achieved using Custom Property Animation(FractionLinearLayout.java class given below). My app has several Fragment, switching among these fragment is followed by a right to left slide animation. Everything is working perfect untill i disable animation from Developer Options for testing purpose.
Nothing appears when i disable animations. I can see logcats means app is working perfect just views are not being loaded, (May be) because of the custom properties FractionTranslationX and FractionTranslationY.
Has anyone gone through this problem? Thanks in advance.
FractionLinearLayout.java: custom class for animation
public class FractionLinearLayout extends LinearLayout {
DisplayMetrics matrics = getContext().getResources().getDisplayMetrics();
public FractionLinearLayout(Context context, AttributeSet attrs,
int defStyleAttr) {
super(context, attrs, defStyleAttr);
// TODO Auto-generated constructor stub
}
public FractionLinearLayout(Context context) {
super(context);
// TODO Auto-generated constructor stub
}
public FractionLinearLayout(Context context, AttributeSet attrs) {
super(context, attrs);
// TODO Auto-generated constructor stub
}
public float getFractionTranslationX() {
return getWidth() > 0 ? super.getTranslationX() / getWidth() : Float.MAX_VALUE;
}
public void setFractionTranslationX(float translationX) {
int width = getWidth();
super.setTranslationX(width > 0 ? width * translationX : Float.MAX_VALUE);
}
public float getFractionTranslationY() {
return getHeight() > 0 ? super.getTranslationX() / getHeight() : Float.MAX_VALUE;
}
public void setFractionTranslationY(float translationY) {
int height = getHeight();
super.setTranslationY(height > 0 ? height * translationY : Float.MAX_VALUE);
}
public float getAnimWidth() {
return getLayoutParams().width;
}
public void setAnimWidth(int animWidth) {
getLayoutParams().width = animWidth;
requestLayout();
}
}
layout file of fragment:
fragment_main_layout.xml
<?xml version="1.0" encoding="utf-8"?>
<com.bbi.views.FractionLinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#drawable/esc_app_background"
android:orientation="vertical">
...........
...........
</com.bbi.views.FractionLinearLayout>
Custom animation xml file:
alide_in_left.xml
<?xml version="1.0" encoding="utf-8"?>
<set
xmlns:android="http://schemas.android.com/apk/res/android"
android:interpolator="#android:anim/decelerate_interpolator">
<objectAnimator xmlns:android="http://schemas.android.com/apk/res/android"
android:duration="#integer/animation_time"
android:propertyName="fractionTranslationX"
android:valueFrom="1"
android:valueTo="0"
android:valueType="floatType" />
</set>
slide_out_left.xml
<?xml version="1.0" encoding="utf-8"?>
<set
xmlns:android="http://schemas.android.com/apk/res/android"
android:interpolator="#android:anim/accelerate_interpolator">
<objectAnimator xmlns:android="http://schemas.android.com/apk/res/android"
android:duration="#integer/animation_time"
android:propertyName="fractionTranslationX"
android:valueFrom="0"
android:valueTo="-1"
android:valueType="floatType" />
</set>
Code to add fragment on Activity:
getFragmentManager().beginTransaction()
.setCustomAnimations(R.anim.slide_in_left;, R.anim.slide_out_left)
.replace(R.id.frameTopContainer, newsToolFragment)
.commitAllowingStateLoss();
When i replace com.views.FractionLinearLayout to LinearLayout in fragment_main_layout.xml, everything works fine(not animation obvious as i have disabled animation and removed property custom animation).
Finally solved my issue by reading animation_scale flag and removing setCustomAnimations() method according to that.
The problem is when you disabled the animation, the animator will call setFractionTranslationX() to pass the initial value and final value at the same time, and it would be a very early moment that your view not yet have width and height, so you will translated your view to Float.MAX_VALUE every time.
To correctly set your view x and y position whenever animation enable or not, you can :
private float mXFraction;
private float mYFraction;
#Override
protected void onLayout(boolean changed, int l, int t, int r, int b) {
super.onLayout(changed, l, t, r, b);
setFractionTranslationX(mXFraction);
setFractionTranslationY(mYFraction);
}
public float getFractionTranslationX() {
return mXFraction;
}
public void setFractionTranslationX(float xFraction) {
mXFraction = xFraction;
int width = getWidth();
if (width > 0) setTranslationX(xFraction * width);
}
public float getFractionTranslationY() {
return mYFraction;
}
public void setFractionTranslationY(float yFraction) {
mYFraction = yFraction;
int height = getHeight();
if (height > 0) setTranslationY(yFraction * height);
}

Why does the animation gets stuck on Android sometimes?

I have been trying to animate view in android and I have done that animation but that problem is that some times the animation stuck in the middle I don't know why.
what I am doing is I have a view in the middle and that view contains horizontal list view and when an item is clicked the view animates to the top and on the top when user clicks it goes down to its original position
here is the code for animation.
public class DropDownAnim extends Animation {
private final float targetHeight;
private final View view;
private final boolean down;
public DropDownAnim(View view, float targetHeight, boolean down) {
this.view = view;
this.targetHeight = targetHeight;
this.down = down;
}
#Override
protected void applyTransformation(float interpolatedTime, Transformation t) {
int newHeight;
if (down) {
newHeight = (int) (targetHeight * interpolatedTime);
} else {
newHeight = (int) (targetHeight * (1 - interpolatedTime));
}
view.getLayoutParams().height = newHeight;
view.requestLayout();
}
#Override
public void initialize(int width, int height, int parentWidth,
int parentHeight) {
super.initialize(width, height, parentWidth, parentHeight);
}
#Override
public boolean willChangeBounds() {
return true;
}
}
when the view that contains horizontal list view and in that an item is clicked I am doing
DropDownAnim drop = new DropDownAnim(_View, (width_And_Height[1] / 100) *
Utils.get_Percentage_For_animate_View_Based_On_Mobile_Resloution(),
true); //true means go to top
drop.setDuration(DURATION);
_View.setAnimation(drop);
_View.startAnimation(drop);
and when the view is on the top
DropDownAnim drop = new DropDownAnim(_View, (width_And_Height[1] / 100) * Utils.get_Percentage_For_animate_View_Based_On_Mobile_Resloution(),
false);//false means go to is orignal position
drop.setDuration(DURATION);
_View.setAnimation(drop);
_View.startAnimation(drop);
this is returning the height of the screen.
width_And_Height[1]
first when the horizontal scroll view is in the center and i click on mad it goes up and when the horizontal scroll view is on top and i click on map it comes to its orignal position.
But now the problem is some times the view not come to its orignal position from top and stuck in the middle
here are the images.
when the horizontal scroll view is in the middle of screen
when the horizontal scroll view is on The Top of screen
when the view not come to its original position from top and stuck in the middle
I dont know what is the problem
Thank's for making time for my question,and please HELP :)
I am not sure why you are extending an Animation. If you are trying to change the position or height of a view you should be using PropertyAnimations.
If you are trying to grow a view use a simple ObjectAnimator and do the following.
ObjectAnimator animation = ObjectAnimator.ofFloat(mView,"scaleX",0,2);
animation.setDuration(duration);
animation.start();

Android: expand animation not working

I am using following code to animate expandable layout:
class ExpandAnimation extends Animation {
private View _view;
private int _startHeight;
private int _finishHeight;
public ExpandAnimation( View view, int startHeight, int finishHeight ) {
_view = view;
_startHeight = startHeight;
_finishHeight = finishHeight;
setDuration(500);
System.out.println(_startHeight);
System.out.println(_finishHeight);
}
#Override
protected void applyTransformation( float interpolatedTime, Transformation t ) {
int newHeight = (int)((_finishHeight - _startHeight) * interpolatedTime + _startHeight);
_view.getLayoutParams().height = newHeight;
_view.requestLayout();
}
#Override
public void initialize( int width, int height, int parentWidth, int parentHeight ) {
super.initialize(width, height, parentWidth, parentHeight);
}
#Override
public boolean willChangeBounds( ) {
return true;
}
};
This animation is created every time I click a button. It is called properly (checked System.out.println and it prints correct values) however in emulator animation runs only like once of 15 times. To be exact hiding it works great but expanding works only once a few times (on emulator, cant get it working on phone).
What could be the problem?
Thanks in forward
EDIT: layout I am trying to animate is FrameLayout. It has TextView as child and finishHeight is measured by textView measure height. The values are correct. I have also tried calling textView.requestLayout() in apply transformation to redraw layout but it is not working. It still expands only sometimes. If you need any more code feel free to ask.
Calling
((View) toExpand.getParent()).invalidate();
just after startAnimation solved my problem. Must check it on other devices but I think it will work.

How to animate RecyclerView items when they appear

How can I animate the RecyclerView Items when there are appearing?
The default item animator only animates when a data is added or removed after the recycler data has been set.
How can this be achieved?
EDIT :
According to the ItemAnimator documentation :
This class defines the animations that take place on items as changes are made to the adapter.
So unless you add your items one by one to your RecyclerView and refresh the view at each iteration, I don't think ItemAnimator is the solution to your need.
Here is how you can animate the RecyclerView items when they appear using a CustomAdapter :
public class CustomAdapter extends RecyclerView.Adapter<CustomAdapter.ViewHolder>
{
private Context context;
// The items to display in your RecyclerView
private ArrayList<String> items;
// Allows to remember the last item shown on screen
private int lastPosition = -1;
public static class ViewHolder extends RecyclerView.ViewHolder
{
TextView text;
// You need to retrieve the container (ie the root ViewGroup from your custom_item_layout)
// It's the view that will be animated
FrameLayout container;
public ViewHolder(View itemView)
{
super(itemView);
container = (FrameLayout) itemView.findViewById(R.id.item_layout_container);
text = (TextView) itemView.findViewById(R.id.item_layout_text);
}
}
public CustomAdapter(ArrayList<String> items, Context context)
{
this.items = items;
this.context = context;
}
#Override
public CustomAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType)
{
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.custom_item_layout, parent, false);
return new ViewHolder(v);
}
#Override
public void onBindViewHolder(ViewHolder holder, int position)
{
holder.text.setText(items.get(position));
// Here you apply the animation when the view is bound
setAnimation(holder.itemView, position);
}
/**
* Here is the key method to apply the animation
*/
private void setAnimation(View viewToAnimate, int position)
{
// If the bound view wasn't previously displayed on screen, it's animated
if (position > lastPosition)
{
Animation animation = AnimationUtils.loadAnimation(context, android.R.anim.slide_in_left);
viewToAnimate.startAnimation(animation);
lastPosition = position;
}
}
}
And your custom_item_layout would look like this :
<FrameLayout
android:id="#+id/item_layout_container"
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:id="#+id/item_layout_text"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceListItemSmall"
android:gravity="center_vertical"
android:minHeight="?android:attr/listPreferredItemHeightSmall"/>
</FrameLayout>
For more information about CustomAdapters and RecyclerView, refer to this training on the official documentation.
Problems on fast scroll
Using this method could cause problems with fast scrolling. The view could be reused while the animation is been happening. In order to avoid that is recommendable to clear the animation when is detached.
#Override
public void onViewDetachedFromWindow(final RecyclerView.ViewHolder holder)
{
((CustomViewHolder)holder).clearAnimation();
}
On CustomViewHolder:
public void clearAnimation()
{
mRootLayout.clearAnimation();
}
Old answer :
Give a look at Gabriele Mariotti's repo, I'm pretty sure you'll find what you need. He provides simple ItemAnimators for the RecyclerView, such as SlideInItemAnimator or SlideScaleItemAnimator.
Made Simple with XML only
Visit Gist Link
res/anim/layout_animation.xml
<?xml version="1.0" encoding="utf-8"?>
<layoutAnimation xmlns:android="http://schemas.android.com/apk/res/android"
android:animation="#anim/item_animation_fall_down"
android:animationOrder="normal"
android:delay="15%" />
res/anim/item_animation_fall_down.xml
<set xmlns:android="http://schemas.android.com/apk/res/android"
android:duration="500">
<translate
android:fromYDelta="-20%"
android:toYDelta="0"
android:interpolator="#android:anim/decelerate_interpolator"
/>
<alpha
android:fromAlpha="0"
android:toAlpha="1"
android:interpolator="#android:anim/decelerate_interpolator"
/>
<scale
android:fromXScale="105%"
android:fromYScale="105%"
android:toXScale="100%"
android:toYScale="100%"
android:pivotX="50%"
android:pivotY="50%"
android:interpolator="#android:anim/decelerate_interpolator"
/>
</set>
Use in layouts and recylcerview like:
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/recycler_view"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layoutAnimation="#anim/layout_animation"
app:layout_behavior="#string/appbar_scrolling_view_behavior" />
I animated fading in of Recyclerview items when they first appear as shown in the code below. Perhaps this will be of use to someone.
private final static int FADE_DURATION = 1000; //FADE_DURATION in milliseconds
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
holder.getTextView().setText("some text");
// Set the view to fade in
setFadeAnimation(holder.itemView);
}
private void setFadeAnimation(View view) {
AlphaAnimation anim = new AlphaAnimation(0.0f, 1.0f);
anim.setDuration(FADE_DURATION);
view.startAnimation(anim);
}
You can also replace setFadeAnimation() with the following setScaleAnimation() to animate appearance of items by scaling them from a point:
private void setScaleAnimation(View view) {
ScaleAnimation anim = new ScaleAnimation(0.0f, 1.0f, 0.0f, 1.0f, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
anim.setDuration(FADE_DURATION);
view.startAnimation(anim);
}
The code above has some warts in so far as when you scroll the RecyclerView items always fade or scale. If you wish you can add code to just allow the animation to happen when the fragment or activity containing the RecyclerView is first created (e.g. get the system time on creation and only allow animation for the first FADE_DURATION milliseconds).
I created animation from pbm's answer with little modification to make the aninmation run only once
in the other word the Animation appear with you scroll down only
private int lastPosition = -1;
private void setAnimation(View viewToAnimate, int position) {
// If the bound view wasn't previously displayed on screen, it's animated
if (position > lastPosition) {
ScaleAnimation anim = new ScaleAnimation(0.0f, 1.0f, 0.0f, 1.0f, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
anim.setDuration(new Random().nextInt(501));//to make duration random number between [0,501)
viewToAnimate.startAnimation(anim);
lastPosition = position;
}
}
and in onBindViewHolder call the function
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
holder.getTextView().setText("some text");
// call Animation function
setAnimation(holder.itemView, position);
}
You can add a android:layoutAnimation="#anim/rv_item_animation" attribute to RecyclerView like this:
<android.support.v7.widget.RecyclerView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layoutAnimation="#anim/layout_animation_fall_down"
/>
thanks for the excellent article here:
https://proandroiddev.com/enter-animation-using-recyclerview-and-layoutanimation-part-1-list-75a874a5d213
A good place to start is this:
https://github.com/wasabeef/recyclerview-animators/blob/master/animators/src/main/java/jp/wasabeef/recyclerview/adapters/AnimationAdapter.java
You don't even need the full library, that class is enough.
Then if you just implement your Adapter class giving an animator like this:
#Override
protected Animator[] getAnimators(View view) {
return new Animator[]{
ObjectAnimator.ofFloat(view, "translationY", view.getMeasuredHeight(), 0)
};
}
#Override
public long getItemId(final int position) {
return getWrappedAdapter().getItemId(position);
}
you'll see items appearing from the bottom as they scroll, also avoiding the problem with the fast scroll.
Animating items in the recyclerview when they are binded in the adapter might not be the best idea as that can cause the items in the recyclerview to animate at different speeds. In my case, the item at the end of the recyclerview animate to their position quicker then the ones at the top as the ones at the top have further to travel so it made it look untidy.
The original code that I used to animate each item into the recyclerview can be found here:
http://frogermcs.github.io/Instagram-with-Material-Design-concept-is-getting-real/
But I will copy and paste the code in case the link breaks.
STEP 1: Set this inside your onCreate method so that you ensure the animation only run once:
if (savedInstanceState == null) {
pendingIntroAnimation = true;
}
STEP 2: You will need to put this code into the method where you want to start the animation:
if (pendingIntroAnimation) {
pendingIntroAnimation = false;
startIntroAnimation();
}
In the link, the writer is animating the toolbar icons, so he put it inside this method:
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_main, menu);
inboxMenuItem = menu.findItem(R.id.action_inbox);
inboxMenuItem.setActionView(R.layout.menu_item_view);
if (pendingIntroAnimation) {
pendingIntroAnimation = false;
startIntroAnimation();
}
return true;
}
STEP 3: Now write the logic for the startIntroAnimation():
private static final int ANIM_DURATION_TOOLBAR = 300;
private void startIntroAnimation() {
btnCreate.setTranslationY(2 * getResources().getDimensionPixelOffset(R.dimen.btn_fab_size));
int actionbarSize = Utils.dpToPx(56);
toolbar.setTranslationY(-actionbarSize);
ivLogo.setTranslationY(-actionbarSize);
inboxMenuItem.getActionView().setTranslationY(-actionbarSize);
toolbar.animate()
.translationY(0)
.setDuration(ANIM_DURATION_TOOLBAR)
.setStartDelay(300);
ivLogo.animate()
.translationY(0)
.setDuration(ANIM_DURATION_TOOLBAR)
.setStartDelay(400);
inboxMenuItem.getActionView().animate()
.translationY(0)
.setDuration(ANIM_DURATION_TOOLBAR)
.setStartDelay(500)
.setListener(new AnimatorListenerAdapter() {
#Override
public void onAnimationEnd(Animator animation) {
startContentAnimation();
}
})
.start();
}
My preferred alternative:
I would rather animate the whole recyclerview instead of the items inside the recyclerview.
STEP 1 and 2 remains the same.
In STEP 3, as soon as your API call returns with your data, I would start the animation.
private void startIntroAnimation() {
recyclerview.setTranslationY(latestPostRecyclerview.getHeight());
recyclerview.setAlpha(0f);
recyclerview.animate()
.translationY(0)
.setDuration(400)
.alpha(1f)
.setInterpolator(new AccelerateDecelerateInterpolator())
.start();
}
This would animate your entire recyclerview so that it flys in from the bottom of the screen.
Create this method into your recyclerview Adapter
private void setZoomInAnimation(View view) {
Animation zoomIn = AnimationUtils.loadAnimation(context, R.anim.zoomin);// animation file
view.startAnimation(zoomIn);
}
And finally add this line of code in onBindViewHolder
setZoomInAnimation(holder.itemView);
In 2019,
I would suggest putting all the item animations into the ItemAnimator.
Let's start with declaring the animator in the recycler-view:
with(view.recycler_view) {
adapter = Adapter()
itemAnimator = CustomAnimator()
}
Declare the custom animator then,
class CustomAnimator() : DefaultItemAnimator() {
override fun animateAppearance(
holder: RecyclerView.ViewHolder,
preInfo: ItemHolderInfo?,
postInfo: ItemHolderInfo): Boolean{} // declare what happens when a item appears on the recycler view
override fun animatePersistence(
holder: RecyclerView.ViewHolder,
preInfo: ItemHolderInfo,
postInfo: ItemHolderInfo): Boolean {} // declare animation for items that persist in a recycler view even when the items change
}
Similar to the ones above there is one for disappearance animateDisappearance, for add animateAdd, for change animateChange and move animateMove.
One important point would be to call the correct animation-dispatchers inside them.
Just extends your Adapter like below
public class RankingAdapter extends AnimatedRecyclerView<RankingAdapter.ViewHolder>
And add super method to onBindViewHolder
#Override
public void onBindViewHolder(ViewHolder holder, final int position) {
super.onBindViewHolder(holder, position);
It's automate way to create animated adapter like "Basheer AL-MOMANI"
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.ScaleAnimation;
import java.util.Random;
/**
* Created by eliaszkubala on 24.02.2017.
*/
public class AnimatedRecyclerView<T extends RecyclerView.ViewHolder> extends RecyclerView.Adapter<T> {
#Override
public T onCreateViewHolder(ViewGroup parent, int viewType) {
return null;
}
#Override
public void onBindViewHolder(T holder, int position) {
setAnimation(holder.itemView, position);
}
#Override
public int getItemCount() {
return 0;
}
protected int mLastPosition = -1;
protected void setAnimation(View viewToAnimate, int position) {
if (position > mLastPosition) {
ScaleAnimation anim = new ScaleAnimation(0.0f, 1.0f, 0.0f, 1.0f, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
anim.setDuration(new Random().nextInt(501));//to make duration random number between [0,501)
viewToAnimate.startAnimation(anim);
mLastPosition = position;
}
}
}
I think, is better to use it like this: (in RecyclerView adapter override just a one method)
override fun onViewAttachedToWindow(holder: ViewHolder) {
super.onViewAttachedToWindow(holder)
setBindAnimation(holder)
}
If You want every attach animation there in RV.

Categories

Resources