仅日期和月份的Android日期选择器 [英] Android Date selector with only Day and Month
问题描述
我正在寻找一种自定义Android中日期选择器的方法,使其仅显示日期和月份(即没有年份)。
I am looking for a way to customize the Date selector in Android to only show the day and month (i.e. no year).
我正在创建一个基于在>如何显示日期选择器的情况下:
I am creating a dialog based on 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;
但是我一直在((View)dayPicker).setVisibility(View.GONE)上收到Cast异常;
But I keep getting a Cast exception on ((View) dayPicker).setVisibility(View.GONE);
java.lang.ClassCastException:java.lang.String无法转换为
android.view.View
java.lang.ClassCastException: java.lang.String cannot be cast to android.view.View
有什么想法吗?
推荐答案
这去。它的APIv11 +具有更高的API版本。
Here give this a go. Its APIv11+ but there are other ways on lower API versions.
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;
更新的代码:这应该可以完成。
Updated code: This should do the job.
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;
这篇关于仅日期和月份的Android日期选择器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!