Reputation: 773
I want to animate ListView items when they first appear. I have the following viewholder:
public class SimpleViewHolder extends RecyclerView.ViewHolder
{
private TextView simpleTextView;
public SimpleViewHolder(final View itemView, final SimpleAdapter.onItemClickListener listener)
{
super(itemView);
simpleTextView = (TextView) itemView.findViewById(R.id.simple_text);
RotateAnimation rotate = new RotateAnimation(0, 360,
Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF,
0.5f);
rotate.setDuration(1000);
rotate.setRepeatCount( 0 );
simpleTextView.setAnimation(rotate);
}
public void bindData(final SimpleViewModel viewModel)
{
simpleTextView.setText( viewModel.getSimpleText() );
}
}
Everything works great, except instead of setting the animations programmatically, I would like to load them from an XML file using the following method:
Animation animation = AnimationUtils.loadAnimation(getApplicationContext(), R.anim.myanimation);
But I'm not clear how to get/pass the context to the RecyclerView.ViewHolder or is this even the proper place where to do animations.
How can I load the XML animation within the RecyclerView.ViewHolder and is this correct place for doing animations for the list items? Thanks!
Upvotes: 0
Views: 1730
Reputation: 2274
you can use itemView.context()
to get the context
just context() is enough
Upvotes: 3
Reputation: 76579
the proper way to obtain the Context
might be eg. within the implementation of onLongClick()
:
@Override
public boolean onLongClick(View viewHolder) {
this.mRecyclerView = (SomeLinearView) viewHolder.getParent();
Context context;
if(viewHolder.isInEditMode()) {
context = ((ContextThemeWrapper) this.mRecyclerView.getContext()).getBaseContext();
} else {
context = this.mRecyclerView.getContext();
}
}
and this does not crash in edit-mode (which is the XML preview). declaring all the variables as final
is merely useless and often hindering, unless being required to do so, because of changing the scope.
and one can apply a layout-animation alike:
int resId = R.anim.some_animation;
LayoutAnimationController animation = AnimationUtils.loadLayoutAnimation(context, resId);
this.mRecyclerView.setLayoutAnimation(animation);
Upvotes: 0
Reputation: 1032
I don't disagree with the placing of animation. I think it's the correct place. About context, I would send it in the constructor.
public SimpleViewHolder(final View itemView, final SimpleAdapter.onItemClickListener listener, Context context) {
//use this context...
}
if your Recyclerview has no context then you can pass context to Recycleview as well. I dont think there is another way around
Upvotes: 0