1.实现效果预期
2.实现
2.1设置基本样式android:datePickerMode="spinner"。
<DatePicker
android:id="@+id/dp_date"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:calendarViewShown="false"
android:datePickerMode="spinner"
/>
2.2 代码调整自定义样式
首先隐藏分割线(将分割线设置为透明);然后设置背景图片改为自己想要的样式。调整年月日之间的间距便于将文字年月日放进去,年月日文字写入一个布局,浮在DatePicker上方,调整间距即可实现如图样式。
//自定义样式
private void setDatePickerDividerColor(DatePicker datePicker) {
// 获取 mSpinners
LinearLayout llFirst = (LinearLayout) datePicker.getChildAt(0);
// 获取 NumberPicker
LinearLayout mSpinners = (LinearLayout) llFirst.getChildAt(0);
for (int i = 0; i < mSpinners.getChildCount(); i++) {
NumberPicker picker = (NumberPicker) mSpinners.getChildAt(i);
//调整年月日之间的间距
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(80, LinearLayout.LayoutParams.WRAP_CONTENT);
params.setMargins(30, 0, 30, 0);
picker.setLayoutParams(params);
//设置分割线颜色为透明
Field[] pickerFields = NumberPicker.class.getDeclaredFields();
for (Field pf : pickerFields) {
if (pf.getName().equals("mSelectionDivider")) {
pf.setAccessible(true);
try {
//设置分割线颜色为透明
pf.set(picker, new ColorDrawable(Color.TRANSPARENT));
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (Resources.NotFoundException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
break;
}
}
//设置背景图片-实现想要的样式
picker.setBackground(context.getDrawable(R.mipmap.XXXX));
//设置选中的picker背景,未选中背景不同
int finalI = i;
picker.setOnScrollListener(new NumberPicker.OnScrollListener() {
@Override
public void onScrollStateChange(NumberPicker view, int scrollState) {
if (scrollState == SCROLL_STATE_TOUCH_SCROLL) {
picker.setBackground(context.getDrawable(R.mipmap.XXXX)); //选中背景图
for (int i = 0; i < mSpinners.getChildCount(); i++) {
NumberPicker picker = (NumberPicker) mSpinners.getChildAt(i);
if(i!=finalI){
//未选中背景图
picker.setBackground(context.getDrawable(R.XXXX1));
}
}
}
}
});
}
//设置年只显示后面两位--eg:22年而非2022年
NumberPicker yearPicker = (NumberPicker) mSpinners.getChildAt(0);
yearPicker.setFormatter(new NumberPicker.Formatter() {
@Override
public String format(int value) {
String year= String.valueOf(value);
return year.substring(2);
}
});
}