当前位置: 代码迷 >> 综合 >> ScrollView 滑动停止监听
  详细解决方案

ScrollView 滑动停止监听

热度:7   发布时间:2023-12-15 11:40:51.0

  遇到一个需求,在ScrollView中设置一个按钮,滑动的时候隐藏,滑动停止之后1秒再重新显示出来。

  由于ScrollView没有提供直接的监听方法,所以要自定义一个ScrollView;实现思路:创建Handler,在ScrollView滑动的时候,先清空所有消息,然后发送延时消息,如果能接收到消息,说明滑动停止,下面是具体实现的代码

package app.view;import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.support.v4.widget.NestedScrollView;
import android.util.AttributeSet;/**Created by XiaoDaAn on 2020/04/02 */
public class ObservableScrollView extends NestedScrollView
{private OnScrollStatusListener onScrollStatusListener;public ObservableScrollView(Context context) {super(context);}public ObservableScrollView(Context context, AttributeSet attrs) {super(context, attrs);}public ObservableScrollView(Context context, AttributeSet attrs, int defStyleAttr) {super(context, attrs, defStyleAttr);}@Override protected void onScrollChanged(int l, int t, int oldl, int oldt) {super.onScrollChanged(l, t, oldl, oldt);if (onScrollStatusListener != null) {onScrollStatusListener.onScrolling();mHandler.removeCallbacksAndMessages(null);mHandler.sendEmptyMessageDelayed(0x01, 200);}}public void setOnScrollStatusListener(OnScrollStatusListener onScrollStatusListener) {this.onScrollStatusListener = onScrollStatusListener;}private Handler mHandler = new Handler() {@Override public void handleMessage(Message msg) {super.handleMessage(msg);switch (msg.what) {case 0x01:if (onScrollStatusListener != null) {onScrollStatusListener.onScrollStop();}break;}}};@Override protected void onDetachedFromWindow() {super.onDetachedFromWindow();mHandler.removeCallbacksAndMessages(null);}public interface OnScrollStatusListener {void onScrollStop();void onScrolling();}
}

在代码中调用:

@BindView(R.id.sv_cjf1)
ObservableScrollView sv_cjf1;//ScrollView滑动停止监听sv_cjf1.setOnScrollStatusListener(new ObservableScrollView.OnScrollStatusListener(){@Overridepublic void onScrollStop(){//滑动停止 1秒后显示按钮if(isHasPos !=1){    //后台返回数据  判断是否需要展示这个按钮Handler handler = new Handler();handler.postDelayed(new Runnable() {@Overridepublic void run() {iv_cj_guide.setVisibility(View.VISIBLE);}}, 1000);}}@Overridepublic void onScrolling(){//滑动中 隐藏按钮if(isHasPos!=1){ //后台返回数据  判断是否需要展示这个按钮iv_cj_guide.setVisibility(View.GONE);}}});

参考https://www.jianshu.com/p/208952db0205