Android NumberPicker 修改分割线颜色和高度及字体颜色大小

时间:2021-07-04 06:16:42

(1)重写NumberPicker已达到修改显示字体颜色大小

public class TextColorNumberPicker extends NumberPicker {

    public TextColorNumberPicker(Context context) {
super(context);
} public TextColorNumberPicker(Context context, AttributeSet attrs) {
super(context, attrs);
} public TextColorNumberPicker(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
} @Override
public void addView(View child) {
super.addView(child);
updateView(child);
} @Override
public void addView(View child, int index,
android.view.ViewGroup.LayoutParams params) {
super.addView(child, index, params);
updateView(child);
} @Override
public void addView(View child, android.view.ViewGroup.LayoutParams params) {
super.addView(child, params);
updateView(child);
} public void updateView(View view) {
if (view instanceof EditText) {
//这里修改显示字体的属性,主要修改颜色
((EditText) view).setTextColor(Color.parseColor("#BAA785"));
}
}
}

(2)修改分割线颜色,需要在初始化控件后,通过反射进行动态设置颜色。

**********注意:在NumberPicker 的 setDisplayedValues调用后调用如下方法:

 private void setNumberPickerDividerColor(NumberPicker numberPicker) {
NumberPicker picker = numberPicker;
Field[] pickerFields = NumberPicker.class.getDeclaredFields();
for (Field pf : pickerFields) {
if (pf.getName().equals("mSelectionDivider")) {
pf.setAccessible(true);
try {
//设置分割线的颜色值 透明
pf.set(picker, new ColorDrawable(this.getResources().getColor(android.R.color.transparent)));
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (Resources.NotFoundException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
break;
}
}
}

注意:修改分割线的高度:查看NumberPicker,找到mSelectionDividerHeight属性,修改:

 // 分割线高度
for (Field pf : pickerFields) {
if (pf.getName().equals("mSelectionDividerHeight")) {
pf.setAccessible(true);
try {
int result = 1;
pf.set(picker, result);
} catch (Exception e){
e.printStackTrace();
}
break;
}
}

(3)使用NumberPicker 注意:

 // 禁止点击后打开键盘
picker.setDescendantFocusability(NumberPicker.FOCUS_BLOCK_DESCENDANTS);
// 设置最大值、最小值 已达到显示所有符合条件的数值
picker.setMaxValue(array.length - 1);
picker.setMinValue(0);

(4) List 转换为 Array[], 以便NumberPicker设置setDisplayedValues(String[]):

String[] array = new String[list.size()];
list.toArray(array);

连接:http://my.oschina.net/yaly/blog/532153