仅包含日期和月份的Android日期选择器
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了仅包含日期和月份的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)上获得Cast异常;
java.lang.ClassCastException:java.lang.String无法强制转换为android.view.View
有任何想法吗?
答案
在这里一试。它的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;
另一答案
这对我有用:
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();
以上是关于仅包含日期和月份的Android日期选择器的主要内容,如果未能解决你的问题,请参考以下文章