RecyclerView處理鼠標滑輪滑動事件

項目進行中,遇到了RecyclerView的Item無法根據鼠標滑輪進行滑動問題,對于RecyclerView的滑動體驗較差,因此撰寫此博客分享RecyclerView鼠標滑輪事件解決方案。

  1. 重寫RecyclerView的onGenericMotionEvent事件,針對事件中的ACTION_SCROLL進行處理

  2. 通過event.getAxisValue(MotionEvent.AXIS_VSCROLL)獲取設備屏幕相對位置,通過RecyclerViewy的scrollBy方法滑動RecyclerView位置,代碼如下:

     public class CustomRecyclerView extends RecyclerView {
             private float mVerticalScrollFactor = 20.f;
    
             public CustomRecyclerView(Context context) {
                 super(context);
             }
    
             public CustomRecyclerView(Context context, @Nullable AttributeSet attrs, int defStyle) {
                 super(context, attrs, defStyle);
             }
    
              public CustomRecyclerView(Context context, @Nullable AttributeSet attrs) {
                 super(context, attrs);
             }
    
             @TargetApi(Build.VERSION_CODES.HONEYCOMB_MR1)
             @Override
                 public boolean onGenericMotionEvent(MotionEvent event) {//鼠標滑輪滑動事件
                  if ((event.getSource() & InputDevice.SOURCE_CLASS_POINTER) != 0) {
                      if (event.getAction() == MotionEvent.ACTION_SCROLL &&
                           getScrollState() == SCROLL_STATE_IDLE) {//鼠標滑輪事件執行&&RecyclerView不是真正滑動
                          final float vscroll = event.getAxisValue(MotionEvent.AXIS_VSCROLL);//獲取軸線距離
                         if (vscroll != 0) {
                          final int delta = -1 * (int) (vscroll * mVerticalScrollFactor);
                          if (ViewCompat.canScrollVertically(this, delta > 0 ? 1 : -1)) {
                           scrollBy(0, delta);
                           return true;
                 }
             }
         }
     }
             return super.onGenericMotionEvent(event);
         }
     }
    

ListView嵌套ScrollView滑動事件沖突

項目進行中會遇到ScrollView嵌套ListView,ScrollView不可滑動情況,解決此問題的方法主要有:

  1. 重寫ListView的onMeasure方法讓ListView高度達到最大,實現根據Item自適應效果,代碼如下:

     public class ListViewForScrollView extends ListView {
          public ListViewForScrollView(Context context) {
              super(context);
      }
    
         public ListViewForScrollView(Context context, AttributeSet attrs) {
              super(context, attrs);
      }
    
     public ListViewForScrollView(Context context, AttributeSet attrs,
                              int defStyle) {
         super(context, attrs, defStyle);
     }
    
      @Override
     /**
       * 重寫該方法,達到使ListView適應ScrollView的效果
     */
      protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
          int expandSpec = MeasureSpec.makeMeasureSpec(Integer.MAX_VALUE >> 2,
             MeasureSpec.AT_MOST);
         super.onMeasure(widthMeasureSpec, expandSpec);
      }
         }
    
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容