2014-02-17 103 views
8

我正在寻找一种方法来自定义Android中的日期选择器,以仅显示日期和月份(即无年份)。只有日期和月份的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)一个演员例外;

java.lang.ClassCastException:java.lang.String中不能转换到 android.view.View

任何想法?

回答

17

这里给出一个去。它的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; 
+0

我将yearPicker更改为查看yearPicker = dlg.findViewById(year);以避免API级别的问题,但它符合但返回null。有任何想法吗? – checklist

+0

更新了代码。 – Simon

+2

也适用于棒棒糖! –

相关问题