前言
今天在播放器中,突然想到了如果列表项过多,那么用户手指连续滑着回到顶部未免太累!类似微信朋友圈的双击TitleBar返回顶部,既然微信这超级App都实现了,那还等什么呢?动手做起来吧。我们这里是双击Toolbar返回顶部,不仅如此,其实在回调方法中可以做自己想做的事情。
预览图
SuperToolbar.java代码:
public class SuperToolbar extends Toolbar implements TapListener.OnDoubleTapListener {private OnTwoTapListener mOnTwoTapListener;private GestureDetector mDetector;public interface OnTwoTapListener {void onTwoTap();}public void setOnTwoTapListener(OnTwoTapListener onTwoTapListener) {mOnTwoTapListener = onTwoTapListener;}public SuperToolbar(Context context) {this(context, null);}public SuperToolbar(Context context, @Nullable AttributeSet attrs) {this(context, attrs, android.support.v7.appcompat.R.attr.toolbarStyle);}public SuperToolbar(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {super(context, attrs, defStyleAttr);TapListener tapListener = new TapListener(this);mDetector = new GestureDetector(context, tapListener);}public void onDouble() {mOnTwoTapListener.onTwoTap();}public boolean onTouchEvent(MotionEvent ev) {super.onTouchEvent(ev);mDetector.onTouchEvent(ev);return true;}}
TapListener 是 GestureDetector.SimpleOnGestureListener 的子类,我们需要它的 onDoubleTap(MotionEvent e) 方法 , SuperToolbar 实现了TapListener.OnDoubleTapListener这个接口,用于触发 onDoubleTap 这个双击方法。
TapListener.java源码:
public class TapListener extends GestureDetector.SimpleOnGestureListener {private OnDoubleTapListener mDoubleTapListener;public TapListener(OnDoubleTapListener onDoubleTapListener) {mDoubleTapListener = onDoubleTapListener;}public interface OnDoubleTapListener {void onDouble();}public boolean onDoubleTap(MotionEvent e) {mDoubleTapListener.onDouble();return true;}}
使用方法
SuperToolbar toolbar = (SuperToolbar) actView.findViewById(R.id.tool_bar);toolbar.setOnTwoTapListener(new SuperToolbar.OnTwoTapListener() {public void onTwoTap() {//我的一个工具显示Toast,在双击后让RecyclerView返回列表顶部// 在这里可以干你自己想干的事情,whatever,who care!mUtils.sToast("双击!双击!Toolbar!");mRecycler.smoothScrollToPosition(0);}});
结语
今天写的这两篇博文记录的代码都是非常简单实用,用起来也很方便。大家有问题的话,可以看下面的联系方式找到我,我们一起讨论。
关于我
- 微博:@安卓猴
- 微信公众号:Android奇想录(android_amazing)