WheelView icon indicating copy to clipboard operation
WheelView copied to clipboard

设置数据后无法自行选中,回调失效,原因是itemH高度为0

Open DongDian455 opened this issue 3 years ago • 0 comments

下面这个代码有点问题,因为如果第一次回调childcount还没设置数据,那么这个监听就被移除了

 private void addOnGlobalLayoutListener() {
        getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver
                .OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
                    getViewTreeObserver().removeOnGlobalLayoutListener(this);
                } else {
                    getViewTreeObserver().removeGlobalOnLayoutListener(this);
                }
                if (getChildCount() > 0 && mItemH == 0) {
                    mItemH = getChildAt(0).getHeight();
                    if (mItemH != 0) {
                        ViewGroup.LayoutParams params = getLayoutParams();
                        params.height = mItemH * mWheelSize;
                        refreshVisibleItems(getFirstVisiblePosition(),
                                getCurrentPosition() + mWheelSize / 2,
                                mWheelSize / 2);
                        setBackground();
                    } else {
                        throw new WheelViewException("wheel item is error.");
                    }
                }
            }
        });

由于上面监听没获取到mItemH的高度,那么下面这个刷新的方法就不会执行了,因为高度是0

    /**
     * 刷新当前位置
     *
     * @param join
     */
    private void refreshCurrentPosition(boolean join) {
        if (getChildAt(0) == null || mItemH == 0) {
            return;
   .................
}

我的解决思路是这样,获取到高度才移除监听

private void addOnGlobalLayoutListener() {
        getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver
                .OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                if(mItemH!=0){
                    getViewTreeObserver().removeOnGlobalLayoutListener(this);
                }
                if (getChildCount() > 0 && mItemH == 0) {
                    mItemH = getChildAt(0).getHeight();
                    if (mItemH != 0) {
                        ViewGroup.LayoutParams params = getLayoutParams();
                        params.height = mItemH * mWheelSize;
                        refreshVisibleItems(getFirstVisiblePosition(),
                                getCurrentPosition() + mWheelSize / 2,
                                mWheelSize / 2);
                        setBackground();
                    } else {
                        throw new WheelViewException("wheel item is error.");
                    }
                }
            }
        });
    }

DongDian455 avatar Aug 30 '21 03:08 DongDian455