DatePicker 日期选择控件 DatePickerDialog 日期选择对话框
1、main.xml的代码:
<RelativeLayout .....>
<TextView
....
android:id="@+id/dateDisplay"
/>
<Button
.....
android:text=
"改变日期"
android:id
=
"@+id/pickDate"
/>
</RelativeLayout>
其中文本框用来显示时间,按钮为了触发日期选择对话框,当然用其他组件来触发日期选择对话框也是的。
2MainActivity.class
public class MainActivty extends Activity{
//准备公用属性
private TextView dateDisplay;
private Button pickDate;
private int mYear;
private int mMonth;
private int mDay;
//准备对话框Id
static final int DATE_DIALOG_ID = 0;
//准备日期设置监听器
private OnDateSetListener dsl = new DatePickerDialog.OnDateSetListener(){
@Override
public void onDateSet(DatePicker view, int year, int monthOfYear,
int dayOfMonth) {
mYear =year;
mMonth= monthOfYear;
mDay= dayOfMonth;
dateDisplay.setText(mYear+"-"+(mMonth+1)+"-"+mDay);
}
};
//重写创建对话框方法
@Override
protected Dialog onCreateDialog(int id){
switch(id){
case DATE_DIALOG_ID:
//把Activity上下文、日期设置监听器、以及日期的年月日都作为参数传给那个新成立的对话框组件
return new DatePickerDialog(this, dsl, mYear, mMonth, mDay);
}
return null;
}
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//得到当前日期
final Calendar c = Calendar.getInstance();
mYear = c.get(Calendar.YEAR);
mMonth = c.get(Calendar.MONTH);
mDay = c.get(Calendar.DAY_OF_MONTH);
//获取xml中的组件
dateDisplay= (TextView)findViewById(R.id.dateDisplay);
pickDate = (Button)findViewById(R.id.pickDate);
//给日期显示组件一个初始值
dateDisplay.setText(mYear+"-"+(mMonth+1)+"-"+mDay);
//给按钮绑定点击监听器
pickDate.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
showDialog(DATE_DIALOG_ID);
}
});
}
}
}
3.运行结果图:
xml属性
XML Attributes | |||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|
Attribute Name | Related Method | Description | |||||||||
android:calendarViewShown | Whether the calendar view is shown. | ||||||||||
android:endYear | The last year (inclusive), for example "2010". | ||||||||||
android:maxDate | The maximal date shown by this calendar view in mm/dd/yyyy format. | ||||||||||
android:minDate | The minimal date shown by this calendar view in mm/dd/yyyy format. | ||||||||||
android:spinnersShown | Whether the spinners are shown. | ||||||||||
android:startYear | The first year (inclusive), for example "1940". |