NumberPicker分隔线的颜色设置

300 阅读1分钟
  1. 之前可以通过反射来更改NumberPicker分隔线的颜色,但是这段代码在android api29+已经无效。
public void setNumberPickerDividerColor(NumberPicker numberPicker) {
    NumberPicker picker = numberPicker;
    Field[] pickerFields = NumberPicker.class.getDeclaredFields();
    for (Field pf : pickerFields) {
        LogUtils.e("Field name",pf.getName());
        if (pf.getName().equals("mSelectionDivider")) {
            pf.setAccessible(true);
            try {
                //设置分割线的颜色值 透明
                pf.set(picker, new ColorDrawable(this.getResources().getColor(R.color.theme_color)));
            } catch (IllegalArgumentException | Resources.NotFoundException | IllegalAccessException e) {
                e.printStackTrace();
            }
            break;
        }
    }
    // 分割线高度
    for (Field pf2 : pickerFields) {
        if (pf2.getName().equals("mSelectionDividerHeight")) {
            pf2.setAccessible(true);
            try {
                int result = 3;
                pf2.set(picker, result);
            } catch (Exception e) {
                e.printStackTrace();
            }
            break;
        }
    }
}

  1. 还有一种是通过theme修改,如下:

首先style.xml添加

<style name="NumberPickerStyle" parent="Theme.AppCompat.Light">
    <item name="colorControlNormal">@color/theme_color</item>
</style>

然后在xml中引用

<NumberPicker
    android:id="@+id/number_picker"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:theme="@style/NumberPickerStyle" />

也可以修改字号和颜色等其他属性

<style name="NumberPickerStyle" parent="Theme.AppCompat.Light">
    <item name="colorControlNormal">@color/theme_color</item>
    <item name="android:textColor">@color/white</item>
    <item name="android:textSize">18sp</item>
</style>