[英]Get context within RecyclerView.ViewHolder
我想為ListView項首次出現時設置動畫。 我有以下觀點者:
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() );
}
}
一切工作都很好,除了不是通過編程方式設置動畫,我想使用以下方法從XML文件加載它們:
Animation animation = AnimationUtils.loadAnimation(getApplicationContext(), R.anim.myanimation);
但是我不清楚如何將上下文獲取/傳遞給RecyclerView.ViewHolder,或者這是否是執行動畫的適當位置。
如何在RecyclerView.ViewHolder中加載XML動畫,這是為列表項制作動畫的正確位置嗎? 謝謝!
您可以使用itemView.getContext()
獲取上下文
我不同意動畫的擺放位置。 我認為這是正確的地方。 關於上下文,我將其發送到構造函數中。
public SimpleViewHolder(final View itemView, final SimpleAdapter.onItemClickListener listener, Context context) {
//use this context...
}
如果您的Recyclerview沒有上下文,那么您也可以將上下文傳遞給Recycleview。 我不認為還有其他辦法
獲取Context
的正確方法可能是例如。 在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();
}
}
並且這不會在編輯模式(XML預覽)下崩潰。 將所有變量聲明為final
只是無用的,並且通常會受到阻礙,除非需要這樣做,因為更改了范圍。
並且可以同樣地應用布局動畫:
int resId = R.anim.some_animation;
LayoutAnimationController animation = AnimationUtils.loadLayoutAnimation(context, resId);
this.mRecyclerView.setLayoutAnimation(animation);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.