Created
December 17, 2015 07:30
-
-
Save osama-raddad/1eb7d4e541c1f9b1efd4 to your computer and use it in GitHub Desktop.
animate RecyclerView
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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.container, 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; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment