世事洞明皆学问,人情练达即文章。这篇文章主要讲述仅包含日期和月份的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有任何想法吗?
答案【仅包含日期和月份的Android日期选择器】在这里一试。它的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();
推荐阅读
- 带有Gcloud错误的Rails((gcloud.preview.app.deploy)错误响应:[13]意外错误。部署版本:)
- 未捕获错误(模块“AppModule”导入的意外指令“MatFormField”。请添加@NgModule注释)
- 如何获得MONTHS,DAYS和周(android datepicker)
- 我需要在android.widget.datepicker中自定义月份名称
- 无法找到Android Studio DatePicker类[重复]
- 如何解决谷歌的Blockly未来的程序员游戏:迷宫级别
- 如何使用Symfony 1.4返回JSON响应
- 如何在PHP的闭包函数中更改范围之外的变量的值
- 如何在Symfony 1.4中获取并显示无效表单的所有错误