高亮显示滚轮控件WheelView选中项

先看效果图

image

本示例基于开源项目android-wheel修改,这个项目已经开源很早,相信很多人也已用过了,最近项目需要将当前选中的item高亮显示,现将我采用的方法分享一下

我们显示的滚轮一般就两种类型(文字或者数字),对应的Adapter分别是ArrayWheelAdapterNumericWheelAdapter,我们只需要重写这两个Adapter即可

文字类型:

public class UnitArrayWheelAdapter extends ArrayWheelAdapter<String> {
    // Index of current item
    int currentItem;
    // Index of item to be highlighted
    int currentValue;

    /**
     * Constructor
     */
    public UnitArrayWheelAdapter(Context context, String[] items, int current) {
        super(context, items);
        this.currentValue = current;
    }

    @Override
    protected void configureTextView(TextView view) {
        super.configureTextView(view);
        if (currentItem == currentValue) {
            view.setTextColor(0xFFFF7500);
            view.setTextSize(18);
        }
        view.setTypeface(Typeface.SANS_SERIF);
    }

    @Override
    public View getItem(int index, View cachedView, ViewGroup parent) {
        currentItem = index;
        return super.getItem(index, cachedView, parent);
    }
}

数字类型:

public class UnitNumericWheelAdapter extends NumericWheelAdapter {
    // Index of current item
    int currentItem;
    // Index of item to be highlighted
    int currentValue;

    /**
     * Constructor
     */
    public UnitNumericWheelAdapter(Context context, int minValue, int maxValue, int current) {
        super(context, minValue, maxValue);
        this.currentValue = current;
    }

    @Override
    protected void configureTextView(TextView view) {
        super.configureTextView(view);
        if (currentItem == currentValue) {
            view.setTextColor(0xFFFF7500);
            view.setTextSize(18);
        }
        view.setTypeface(Typeface.SANS_SERIF);

    }

    @Override
    public View getItem(int index, View cachedView, ViewGroup parent) {
        currentItem = index;
        return super.getItem(index, cachedView, parent);
    }
}

最后需要对wheelview添加滚动监听

wheelview.addChangingListener(new OnWheelChangedListener() {
        @Override
        public void onChanged(WheelView wheel, int oldValue, int newValue) {
             wheel.setViewAdapter(new UnitArrayWheelAdapter(context, strings, current);//important
        }
    });