这是月份选择器的基本示例,但也可以轻松适应选择年份和/或日期(也适用于较旧的 android 版本):
public void initMonthPicker(){
dp_mes = (DatePicker) findViewById(R.id.dp_mes);
int year = dp_mes.getYear();
int month = dp_mes.getMonth();
int day = dp_mes.getDayOfMonth();
dp_mes.init(year, month, day, new DatePicker.OnDateChangedListener() {
@Override
public void onDateChanged(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
month_i = monthOfYear + 1;
Log.e("selected month:", Integer.toString(month_i));
//Add whatever you need to handle Date changes
}
});
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP){
int daySpinnerId = Resources.getSystem().getIdentifier("day", "id", "android");
if (daySpinnerId != 0)
{
View daySpinner = dp_mes.findViewById(daySpinnerId);
if (daySpinner != null)
{
daySpinner.setVisibility(View.GONE);
}
}
int monthSpinnerId = Resources.getSystem().getIdentifier("month", "id", "android");
if (monthSpinnerId != 0)
{
View monthSpinner = dp_mes.findViewById(monthSpinnerId);
if (monthSpinner != null)
{
monthSpinner.setVisibility(View.VISIBLE);
}
}
int yearSpinnerId = Resources.getSystem().getIdentifier("year", "id", "android");
if (yearSpinnerId != 0)
{
View yearSpinner = dp_mes.findViewById(yearSpinnerId);
if (yearSpinner != null)
{
yearSpinner.setVisibility(View.GONE);
}
}
} else { //Older SDK versions
Field f[] = dp_mes.getClass().getDeclaredFields();
for (Field field : f)
{
if(field.getName().equals("mDayPicker") || field.getName().equals("mDaySpinner"))
{
field.setAccessible(true);
Object dayPicker = null;
try {
dayPicker = field.get(dp_mes);
} catch (IllegalAccessException e) {
e.printStackTrace();
}
((View) dayPicker).setVisibility(View.GONE);
}
if(field.getName().equals("mMonthPicker") || field.getName().equals("mMonthSpinner"))
{
field.setAccessible(true);
Object monthPicker = null;
try {
monthPicker = field.get(dp_mes);
} catch (IllegalAccessException e) {
e.printStackTrace();
}
((View) monthPicker).setVisibility(View.VISIBLE);
}
if(field.getName().equals("mYearPicker") || field.getName().equals("mYearSpinner"))
{
field.setAccessible(true);
Object yearPicker = null;
try {
yearPicker = field.get(dp_mes);
} catch (IllegalAccessException e) {
e.printStackTrace();
}
((View) yearPicker).setVisibility(View.GONE);
}
}
}
}