日期选择器(DataPicker)
显示一个可供日期选择的界面
监听器方法init(year,month,day,OnDateChangedListener)
监听器
DataPicker.OnDateChangedListener
下面我们直接看代码:
1.Activity
//日期选择器 public class DatePickerActivity extends Activity { private DatePicker datePicker; protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.date_picker); datePicker = (DatePicker)findViewById(R.id.datePickerId); //获取日历 Calendar c1 = Calendar.getInstance(); // 设置最小的时间年份 c1.set(1990, 0, 1, 0, 0, 0); datePicker.setMinDate(c1.getTimeInMillis()); // 设置最大的时间年份 Calendar c2 = Calendar.getInstance(); c2.set(2020, 11, 31, 23, 59, 59); datePicker.setMaxDate(c2.getTimeInMillis()); //datePicker.init(year, monthOfYear, dayOfMonth, onDateChangedListener)监听器方法 //DatePicker.OnDateChangedListener监听器 datePicker.init(1993,0,1,new DatePicker.OnDateChangedListener() { public void onDateChanged(DatePicker view, int year, int monthOfYear, int dayOfMonth) { Toast.makeText(DatePickerActivity.this, "你选择的日期:"+(year+"-"+(monthOfYear+1)+"-"+dayOfMonth), Toast.LENGTH_SHORT).show(); } }); } }
2.xml布局文件
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" android:padding="5dp" > <!-- 日期选择器 --> <DatePicker android:id="@+id/datePickerId" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center" /> </LinearLayout>
3.效果图显示