網(wǎng)上找了一些跑馬燈實(shí)現(xiàn)都是直接重寫的textview不停的改變繪制文字的位置來(lái)達(dá)到跑馬燈效果,但是有的時(shí)候需求要求來(lái)回滾動(dòng)多條信息,用textview實(shí)現(xiàn)的就不盡人意了,于是用recyclerview整理了一個(gè)
思路就是利用recyclerview的scrollBy不停的滾動(dòng),來(lái)達(dá)到效果
recyclerview代碼
import android.content.Context;
import android.util.AttributeSet;
import android.view.MotionEvent;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.cy.utils.LogUtil;
import java.lang.ref.WeakReference;
public class AutoPollRecyclerView extends RecyclerView {
private static final long TIME_AUTO_POLL = 10;
AutoPollTask autoPollTask;
private boolean running; //標(biāo)示是否正在自動(dòng)輪詢
private boolean canRun;//標(biāo)示是否可以自動(dòng)輪詢,可在不需要的是否置false
public AutoPollRecyclerView(Context context, @Nullable AttributeSet attrs) {
super(context, attrs);
autoPollTask = new AutoPollTask(this);
}
static class AutoPollTask implements Runnable {
private final WeakReference<AutoPollRecyclerView> mReference;
//使用弱引用持有外部類引用->防止內(nèi)存泄漏
public AutoPollTask(AutoPollRecyclerView reference) {
this.mReference = new WeakReference<AutoPollRecyclerView>(reference);
}
@Override
public void run() {
AutoPollRecyclerView recyclerView = mReference.get();
if (recyclerView != null && recyclerView.running && recyclerView.canRun) {
LinearLayoutManager layoutManager = (LinearLayoutManager) recyclerView.getLayoutManager();
int lastVisibleItemPosition = layoutManager.findLastVisibleItemPosition();
if (lastVisibleItemPosition == (Integer.MAX_VALUE - 1))//如果真有人等到一直滾動(dòng)到最大值那就讓他回到頭部重新滾
recyclerView.scrollToPosition(0);
recyclerView.scrollBy(2, 2);
recyclerView.postDelayed(recyclerView.autoPollTask, recyclerView.TIME_AUTO_POLL);
}
}
}
//開啟:如果正在運(yùn)行,先停止->再開啟
public void start() {
if (running)
stop();
canRun = true;
running = true;
postDelayed(autoPollTask, TIME_AUTO_POLL);
}
public void stop() {
running = false;
removeCallbacks(autoPollTask);
}
@Override
public boolean onTouchEvent(MotionEvent e) {
//若果需要觸摸停止就把這里打開
// switch (e.getAction()) {
// case MotionEvent.ACTION_DOWN:
// if (running)
// stop();
// break;
// case MotionEvent.ACTION_UP:
// case MotionEvent.ACTION_CANCEL:
// case MotionEvent.ACTION_OUTSIDE:
// if (canRun)
// start();
// break;
// }
return false;
}
}
其中要注意recyclerview的adapter里面的getItemCount方法要寫成最大值舀锨,
@Override
public void onBindViewHolder(BaseViewHolder holder, int position) {
String data = mData.get(position % mData.size());
holder.setText(R.id.tv_txt, data);
}
@Override
public int getItemCount() {
return Integer.MAX_VALUE;
}