Android 重写DatePicker------只显示 年-月

来源:互联网 发布:淘宝美姿堂美妆真假 编辑:程序博客网 时间:2024/05/16 09:58


代码不多,话不多说




/** * 重写datePicker 1.只显示 年-月 2.title 只显示 年-月 * @author lmw */public class MonPickerDialog extends DatePickerDialog {public MonPickerDialog(Context context, OnDateSetListener callBack, int year, int monthOfYear, int dayOfMonth) {super(context, callBack, year, monthOfYear, dayOfMonth);this.setTitle(year + "年" + (monthOfYear + 1) + "月");((ViewGroup) ((ViewGroup) this.getDatePicker().getChildAt(0)).getChildAt(0)).getChildAt(2).setVisibility(View.GONE);}@Overridepublic void onDateChanged(DatePicker view, int year, int month, int day) {super.onDateChanged(view, year, month, day);this.setTitle(year + "年" + (month + 1) + "月");}}


调用和赋值:

代码里的mon_date_filter 是调用picker的控件(button或者textView)

public void showMonPicker() {final Calendar localCalendar = Calendar.getInstance();localCalendar.setTime(DateUtils.strToDate("yyyy-MM", mon_date_filter.getText().toString()));new MonPickerDialog(this,new DatePickerDialog.OnDateSetListener() {@Overridepublic void onDateSet(DatePicker view, int year,int monthOfYear, int dayOfMonth) {localCalendar.set(1, year);localCalendar.set(2, monthOfYear);mon_date_filter.setText(DateUtils.clanderTodatetime(localCalendar, "yyyy-MM"));}}, localCalendar.get(1), localCalendar.get(2),localCalendar.get(5)).show();}


用到的两个日期格式化方法

// 字符串类型日期转化成date类型public static Date strToDate(String style, String date) {SimpleDateFormat formatter = new SimpleDateFormat(style);try {return formatter.parse(date);} catch (ParseException e) {e.printStackTrace();return new Date();}}public static String dateToStr(String style, Date date) {SimpleDateFormat formatter = new SimpleDateFormat(style);return formatter.format(date);}





8 4
原创粉丝点击