DatePickerDialog提供了一个弹出的Dialog供用户选择日期。
在这里分享一下其使用方法,效果图如下:
DatePickerActivity.java
package com.yw.myapiupdate.datepicker; import android.app.Activity; import android.app.DatePickerDialog.OnDateSetListener; import android.os.Bundle; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.DatePicker; import android.widget.Toast; import com.yw.myapiupdate.R; public class DataPickerActivity extends Activity implements OnClickListener{ private Button btn_datepicker; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.datepicker_layout); btn_datepicker = (Button)findViewById(R.id.datepicker_btn_date); btn_datepicker.setOnClickListener(this); } @Override public void onClick(View v) { switch(v.getId()){ case R.id.datepicker_btn_date: DateUtils.getInstance().show(this, new OnDateSetListener() { @Override public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) { Toast.makeText(DataPickerActivity.this, year+"/"+(monthOfYear+1)+"/"+dayOfMonth, Toast.LENGTH_LONG).show(); } }); break; } } }
dialog工具类:
package com.yw.myapiupdate.datepicker; import java.util.Calendar; import com.yw.myapiupdate.R; import android.app.DatePickerDialog; import android.content.Context; /** * 日期和时间弹框工具类 * @author yw-tony * */ public class DateUtils{ public DatePickerDialog myDialog; Calendar calendar = Calendar.getInstance(); private DateUtils(){} private static DateUtils instance = null; public static DateUtils getInstance(){ if(instance == null){ synchronized (DateUtils.class) { if(instance == null){ instance = new DateUtils(); } } } return instance; } /** * 显示日期对话框 */ public void show(Context context,DatePickerDialog.OnDateSetListener callBack){ myDialog = new DatePickerDialog(context, R.style.dialog, callBack, calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DAY_OF_MONTH)); myDialog.show(); } }