2014-02-17 127 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

也適用於棒棒糖! –

相關問題