Android NumberPicker探析

最近项目遇到NumberPicker,原生的显示很不让人满意,需要做些修改,

一、基本设置:

不用多说,

np.setMinValue(0);
np.setMaxValue(60);
np.setValue(0);
因为框内是个EditText,若要避免点击编辑弹出输入法,可设置如下

np.setDescendantFocusability(TimePicker.FOCUS_BLOCK_DESCENDANTS);


如要改变显示数据,如下

String []cityArr={"北京","上海","深圳"};
np.setDisplayedValues(cityArr);

获取选取结果

np.setOnValueChangedListener(new NumberPicker.OnValueChangeListener()
        {
            @Override
            public void onValueChange(NumberPicker picker, int oldVal, int newVal)
            {
                //                Toast.makeText(MainActivity.this,"oldVal:::"+oldVal+"newVal::::"+newVal,Toast.LENGTH_SHORT).show();
                Log.e("number", "oldVal:::"+oldVal+"newVal::::"+newVal);
            }
        });




以上是常用设置,还有些自定义,

如要隐藏两条横线,可利用反射找到NumberPicker的mSelectionDivider属性,这个属性是个Drawable类

可设置其drawable为透明从而隐藏,如下

setNumberPickerDividerColor(np);

 //利用反射,将分割线颜色设置为透明
    private void setNumberPickerDividerColor(NumberPicker numberPicker) {
        NumberPicker picker = numberPicker;
        Field[] pickerFields = NumberPicker.class.getDeclaredFields();
        for (Field field : pickerFields) {
            if (field.getName().equals("mSelectionDivider")) {//mSelectionDivider是一个drawable
                field.setAccessible(true);
                try {
                    //设置分割线的颜色值
                    field.set(picker, new ColorDrawable(Color.TRANSPARENT));
                    // field.set(picker, new Div)
                } catch (IllegalArgumentException e) {
                    e.printStackTrace();
                } catch (Resources.NotFoundException e) {
                    e.printStackTrace();
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                }
                break;
            }
        }
    }


如要设置框内字体颜色

可自定义一个类继承NumberPicker

public class MyNumberPicker extends NumberPicker
{
    public MyNumberPicker(Context context)
    {
        super(context);
    }

    public MyNumberPicker(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public MyNumberPicker(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    @Override
    public void addView(View child)
    {
        super.addView(child);
        changeTextColor(child);

    }

    @Override
    public void addView(View child, int index, ViewGroup.LayoutParams params)
    {
        super.addView(child, index, params);
        changeTextColor(child);
    }

    private void changeTextColor(View view)
    {
        if(view instanceof EditText){
            ( (EditText)view ).setTextColor(Color.parseColor("#ff0000"));
        }
    }


}

当然,这些还是不能满足千奇百怪的个性化需求,如增加显示条目,自定义选中字体颜色  等等,还需努力!!!!













你可能感兴趣的:(Android NumberPicker探析)