在我的recyclerView
适配器中,我实现了15秒的简单CountDownTimer,在此实现中,CountDownTimer工作正常,在recylcerview
列表中,我在布局视图中有一些countDownTimer,我想启动和停止此countDownTimer当具有countDownTimer的当前行再次开始并且countDownTimer不可见或未在列表中显示时,必须停止该行。喜欢Instagram播放和停止视频
简化的适配器:
public class InstagramFeedsAdapter extends RecyclerView.Adapter<InstagramFeedsAdapter.InstagramFeedsViewHolder> {
...
@Override
public void onBindViewHolder(final InstagramFeedsViewHolder holder, int position) {
holder.bind(position);
}
public class InstagramFeedsViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
...
private boolean expanded;
private CountDownTimer timer;
public InstagramFeedsViewHolder(View itemView) {
super(itemView);
itemView.setOnClickListener(this);
ButterKnife.bind(this, itemView);
}
@Override
public void onClick(View v) {
}
public void bind(int position) {
if (timer != null) {
timer.cancel();
}
timer = new CountDownTimer(15000, 1000) {
@SuppressLint("DefaultLocale")
@Override
public void onTick(long leftTimeInMilliseconds) {
pager_count_down_timer.setVisibility(View.VISIBLE);
long seconds = leftTimeInMilliseconds / 1000;
pager_count_down_timer.setText(String.format("%02d", seconds % 60));
}
@Override
public void onFinish() {
pager_count_down_timer.setVisibility(View.GONE);
timer = null;
}
}.start();
}
}
现在如何在可见性项目上启动和停止此countDownTimer?
答案 0 :(得分:0)
您的代码存在的问题是,只要绑定default
并从ViewHolder
取消绑定,RecyclerView
就会从头开始,除非CountDownTimer
不回收在这种情况下,使用ViewHolder
的意义不大。
您应该做的是从RecyclerView
中删除Timer
的关联,并将其附加到适配器列表中。这样,您就可以分别跟踪每个项目中计时器经过的时间。
您可以在ViewHolder
中使用 onViewAttachedToWindow(VH holder)
和 onViewDetachedFromWindow(VH holder)
来启动或停止/暂停RecyclerView.Adapter
然后,您可以使用 Timer
更新适配器列表。
答案 1 :(得分:0)
instagram_feeds.addOnScrollListener(new RecyclerView.OnScrollListener() {
@Override
public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
super.onScrolled(recyclerView, dx, dy);
int firstVisibleItem = layoutManager.findFirstCompletelyVisibleItemPosition();
if (lastPos == firstVisibleItem) {
return; //to prevent timer to restart if row position not changed
}
lastPos = firstVisibleItem;
if (mCounter != null) {
mCounter.cancel();
}
final InstagramFeedsAdapter.InstagramFeedsViewHolder vh = (InstagramFeedsAdapter.InstagramFeedsViewHolder) instagram_feeds
.findViewHolderForAdapterPosition(firstVisibleItem);
mCounter = new CountDownTimer(15000, 1000) {
@SuppressLint("DefaultLocale")
@Override
public void onTick(long leftTimeInMilliseconds) {
vh.pager_count_down_timer.setVisibility(View.VISIBLE);
long seconds = leftTimeInMilliseconds / 1000;
vh.pager_count_down_timer.setText(String.format("%02d", seconds % 60));
}
@Override
public void onFinish() {
vh.pager_count_down_timer.setVisibility(View.GONE);
mCounter = null;
}
}.start();
}
});