创建DatePickerDialog的步骤?
1.声明一个监听器,使用匿名内部类。
2.复写onCreateDialog()方法。
3.在需要的时候调用showDialog方法。
MainActivity.java:
package com.mycompany.datepicker;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.DatePicker;
public class MainActivity extends AppCompatActivity {
private Button showDatePicker;
private static final int DATE_PICKER_ID = 1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
showDatePicker = (Button) findViewById(R.id.showDatePicker);
showDatePicker.setOnClickListener(new ButtonListener());
}
private class ButtonListener implements View.OnClickListener{
@Override
public void onClick(View v) {
// 此方法用于显示DatePickerDialog
showDialog(DATE_PICKER_ID);
}
}
DatePickerDialog.OnDateSetListener onDateSetListener
= new DatePickerDialog.OnDateSetListener() {
@Override
public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
int month = monthOfYear + 1;
System.out.println(year + "-" + month + "-" + dayOfMonth);
}
};
@Override
protected Dialog onCreateDialog(int id) {
switch (id){
case DATE_PICKER_ID:
return new DatePickerDialog(this, onDateSetListener, 2016, 0, 1);
}
return null;
}
}