1.第一步创建class,类名自己取,这里我使用DatePickerFragment1
import android.app.DatePickerDialog; import android.app.Dialog; import android.app.DialogFragment; import android.os.Bundle; import android.widget.DatePicker; import java.util.Calendar; /** * Created by mac on 17/6/7. */ public class DatePickerFragment1 extends DialogFragment implements DatePickerDialog.OnDateSetListener{ public OnDateInputListener onDateInputListener; //创建接口类 public interface OnDateInputListener { //接口函数 public void getDate(int year, int month, int day); } public void setOnDateInputListener(OnDateInputListener onDateInputListener) { this.onDateInputListener = onDateInputListener; } @Override public Dialog onCreateDialog(Bundle savedInstanceState) { // Use the current date as the default date in the picker final Calendar c = Calendar.getInstance(); int year = c.get(Calendar.YEAR); int month = c.get(Calendar.MONTH); int day = c.get(Calendar.DAY_OF_MONTH); // Create a new instance of DatePickerDialog and return it return new DatePickerDialog(getActivity(), this, year, month, day); } public void onDateSet(DatePicker view, int year, int month, int day) { // Do something with the date chosen by the user onDateInputListener.getDate(year, month + 1, day); } }
2.第二步实现接口类
implements DatePickerFragment1.OnDateInputListener
3.第三步创建监听
DatePickerFragment1 newFragment = new DatePickerFragment1(); newFragment.show(getFragmentManager(), "datePicker"); newFragment.setOnDateInputListener(this);
4.第四部实现接口的方法
public void getDate(int year, int month, int day){ button.setText(year+"-"+month+"-"+day); }
使用:
DialogFragment dialogFragment1 = new DatePickerFragment(); dialogFragment1.show(getFragmentManager(), "datePicker");
<item name="android:datePickerDialogTheme">@style/style_date_picker_dialog</item>
</style>
<style name="style_date_picker_dialog" parent="@android:style/Theme.DeviceDefault.Light">
<item name="android:windowIsFloating">true</item>
<!--<item name="android:windowBackground">@drawable/dialog_background</item>-->
<item name="android:datePickerStyle">@style/style_datepicker</item>
</style>
<style name="style_datepicker" parent="android:Widget.Material.Light.DatePicker">
<item name="android:datePickerMode">spinner</item>
</style>