自定义DatePickerDialog

时间:2018-09-11 10:28:20

标签: android datepicker

我想为日期选择器设置自定义布局。

这是我的DialogFragment:

public class MyDatePickerFragment extends DialogFragment
        implements DatePickerDialog.OnDateSetListener {
        DatePickerDialog.OnDateSetListener listener;

    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        listener = (DatePickerDialog.OnDateSetListener) getActivity();
        Calendar cal = Calendar.getInstance();
        // Return custom dialog...
        DatePickerDialog dialog =  new DatePickerDialog(Objects.requireNonNull(getActivity()), this, cal.get(Calendar.YEAR)-18, cal.get(Calendar.MONTH), cal.get(Calendar.DAY_OF_MONTH)); //

        return dialog;
    }

    @Override
    public void onDateSet(DatePicker view, int year, int month, int day) {
        // Do something with the date chosen by the user
        listener.onDateSet(view, year, month, day);
    }
}

这是我要设置的自定义布局:

<?xml version="1.0" encoding="utf-8"?>
<DatePicker xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="center"
    android:datePickerMode="spinner"
    android:calendarViewShown="false"
    android:spinnersShown="true">

</DatePicker>

我不知道如何设置它。你怎么做到的?

1 个答案:

答案 0 :(得分:0)

我通过使用OnCreateView代替了我的问题,并在布局中引用了我的选择器和按钮,并在将我的活动分配为实现后调用了onDateSet的侦听器方法。看起来像这样:

public class AwesomeDatePickerFragment extends DialogFragment {
        DatePickerDialog.OnDateSetListener listener;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        View view = inflater.inflate(R.layout.dialog_date_picker, container);
        listener = (DatePickerDialog.OnDateSetListener) getActivity();
        Button btn = view.findViewById(R.id.picker_button);
        final DatePicker picker = view.findViewById(R.id.awesome_date_picker);
        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                listener.onDateSet(picker, picker.getYear(), picker.getMonth(), picker.getDayOfMonth());
                dismiss();
            }
        });
        return view;
    }
}