此方法不好,太复杂了,还是用 viewflipper之类的吧
用RecyclerView 实现跑马灯
用 RecyclerView 实现跑马灯有几点需要注意
Recyclerview 的 smoothScrollToPosition 方法默认效果是直接滑到指定位置,看不到滑动效果,需要重写 LayoutManager 中的 smoothScrollToPosition 方法才能看到缓慢滑动的效果。
public void smoothScrollToPosition(RecyclerView recyclerView, RecyclerView.State state, int position) {
LinearSmoothScroller linearSmoothScroller = new LinearSmoothScroller(recyclerView.getContext()) {
@Override
public PointF computeScrollVectorForPosition(int targetPosition) {
return SmoothScrolLinearLayoutManager.this
.computeScrollVectorForPosition(targetPosition);
}
//This returns the milliseconds it takes to
//scroll one pixel.
@Override
protected float calculateSpeedPerPixel(DisplayMetrics displayMetrics) {
return MILLISECONDS_PER_INCH / displayMetrics.density;
}
};
linearSmoothScroller.setTargetPosition(position);
startSmoothScroll(linearSmoothScroller);
}
要禁掉跑马灯的随手指滑动的效果,也要让 Recyclerview 接收点击事件。可以用以下代码实现。
@Override
public boolean dispatchTouchEvent(MotionEvent ev) {
if (ev.getAction() == MotionEvent.ACTION_UP) {
ev.setAction(MotionEvent.ACTION_DOWN);
mRv.dispatchTouchEvent(ev);
ev.setAction(MotionEvent.ACTION_UP);
mRv.dispatchTouchEvent(ev);
}
super.dispatchTouchEvent(ev);
return true;
}
@Override
public boolean onInterceptTouchEvent(MotionEvent ev) {
if (ev.getAction() == MotionEvent.ACTION_DOWN) {
return true;
}
return super.onInterceptTouchEvent(ev);
}
最终效果如下
screen.gif
网友评论