仅包含日期和月份的Android日期选择器

时间:2014-02-17 20:13:29

标签: android datepicker

我正在寻找一种方法来自定义Android中的日期选择器,仅显示日期和月份(即没有年份)。

我正在创建一个基于How to display date picker for android with only month and year fields?的对话框:

    Dialog dlg = new DatePickerDialog(context, datePickerListener, dueDateCalendar.get(Calendar.YEAR), dueDateCalendar.get(Calendar.MONTH), dueDateCalendar.get(Calendar.DAY_OF_MONTH));
    try {
        Field f[] = dlg.getClass().getDeclaredFields();
        for (Field field : f) {
            String name = field.getName();
            if (name.equals("YEAR")){
                field.setAccessible(true);
                Object dayPicker = new Object();
                dayPicker = field.get(dlg);
                ((View) dayPicker).setVisibility(View.GONE);
            }
        }
    } catch (Exception e){
        // TODO: should not happen
        e.printStackTrace();
    }
    return dlg;

但我一直在((查看)dayPicker).setVisibility(View.GONE);

上获得Cast异常
  

java.lang.ClassCastException:java.lang.String无法强制转换为   android.view.View

有什么想法吗?

2 个答案:

答案 0 :(得分:18)

这里给我一个机会。它的APIv11 +但是在较低的API版本上还有其他方法。

DatePickerDialog dlg = new DatePickerDialog(context, datePickerListener, 
    dueDateCalendar.get(Calendar.YEAR), 
    dueDateCalendar.get(Calendar.MONTH), 
    dueDateCalendar.get(Calendar.DAY_OF_MONTH));
int year = context.getResources().getIdentifier("android:id/year", null, null);
if(year != 0){
    View yearPicker = dlg.getDatePicker().findViewById(year);
    if(yearPicker != null){
        yearPicker.setVisibility(View.GONE);
    }
}
return dlg;

更新的代码:这应该可以胜任。

DatePickerDialog dlg = new DatePickerDialog(context, datePickerListener, 
    dueDateCalendar.get(Calendar.YEAR), 
    dueDateCalendar.get(Calendar.MONTH), 
    dueDateCalendar.get(Calendar.DAY_OF_MONTH))
{
    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        int year = getContext().getResources()
            .getIdentifier("android:id/year", null, null);
        if(year != 0){
            View yearPicker = findViewById(year);
            if(yearPicker != null){
                yearPicker.setVisibility(View.GONE);
            }
        }
    }
};
return dlg;

答案 1 :(得分:0)

这对我有用:

DatePickerDialog monthDatePickerDialog = new DatePickerDialog(activity, 
AlertDialog.THEME_HOLO_LIGHT, new DatePickerDialog.OnDateSetListener() {
    @Override
    public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
        monthTextView.setText(dayOfMonth+ "/" + (month + 1));
    }
}, yearNow, monthNow, dayNow){
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getDatePicker().findViewById(getResources().getIdentifier("year","id","android")).setVisibility(View.GONE);
    }
};
monthDatePickerDialog.setTitle("select_month");
monthDatePickerDialog.show();