RecyclerView 獲取第一個曝光最大的itemposition

 獲取指定view 在屏幕中座標 

    int[] location = new int[2];
 view.getLocationOnScreen(location);
    int x=location[0];//獲取當前位置的橫座標
    int y=location[1];//獲取當前位置的縱座標

豎向滑動:

 public int getCurrentViewIndex(LinearLayoutManager linearLayoutManager) {
        int firstVisibleItem = linearLayoutManager.findFirstVisibleItemPosition();
        int lastVisibleItem = linearLayoutManager.findLastVisibleItemPosition();
        int currentIndex = firstVisibleItem;
        int lastHeight = 0;
        for (int i = firstVisibleItem; i <= lastVisibleItem; i++) {
            View view = linearLayoutManager.getChildAt(i - firstVisibleItem);
            if (null == view) {
                continue;
            }
            int[] location = new int[2];
            view.getLocationOnScreen(location);
            LogUtil.loge(TAG, "-------------------getLocationOnScreen i :" + (i - firstVisibleItem) + "--location[0]:" + location[0] + "---location[1]:" + location[1]);
            Rect localRect = new Rect();
            view.getLocalVisibleRect(localRect);
            LogUtil.loge(TAG, "------------------getLocalVisibleRect:" + "left:" + localRect.left + "----right:" + localRect.right);
            int showHeight = localRect.bottom - localRect.top;
            if (showHeight > lastHeight) {
                currentIndex = i;
                lastHeight = showHeight;
            }
        }
        if (currentIndex < 0) {
            currentIndex = 0;
        }
        return currentIndex;

    }

橫向滑動:

 public int getCurrentViewIndex(LinearLayoutManager linearLayoutManager) {
        int firstVisibleItem = linearLayoutManager.findFirstVisibleItemPosition();
        int lastVisibleItem = linearLayoutManager.findLastVisibleItemPosition();
        int currentIndex = firstVisibleItem;
        int lastWidth = 0;
        for (int i = firstVisibleItem; i <= lastVisibleItem; i++) {
            View view = linearLayoutManager.getChildAt(i - firstVisibleItem);
            if (null == view) {
                continue;
            }
            int[] location = new int[2];
            view.getLocationOnScreen(location);
            LogUtil.loge(TAG, "----------location[0]:" + location[0] + "---location[1]:" + location[1]+"--position:"+(i - firstVisibleItem));
            Rect localRect = new Rect();
            view.getLocalVisibleRect(localRect);
//            LogUtil.loge(TAG, "------------------getLocalVisibleRect:" + "left:" + localRect.left + "----right:" + localRect.right + "--i:" + (i - firstVisibleItem));
            int showWidth = localRect.right - localRect.left;
            if (showWidth > lastWidth) {
                currentIndex = i;
                lastWidth = showWidth;
            }
        }
        if (currentIndex < 0) {
            currentIndex = 0;
        }
        return currentIndex;
    }

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章