对话框的xml:
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="match_parent" android:layout_height="match_parent"> <DatePicker android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/datePicker" android:layout_gravity="center_horizontal" android:calendarViewShown="false"/> <Button android:layout_width="match_parent" android:layout_height="wrap_content" android:text="ACCEPT" android:id="@+id/buttonAccept" /> </LinearLayout>
对话框类:
public class ChooseDate extends DialogFragment implementsView.OnClickListener{ private DatePicker datePicker; private Button acceptButton; private boolean isDateSetted = false; private int year; private int month; private int day; private DateListener listener; public interface DateListener { onDateSelected(int year, int month, int day); } public ChooseDate(){} @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View rootView = inflater.inflate(R.layout.dialog_year_picker, container); getDialog().setTitle(getResources().getString("TITLE")); datePicker = (DatePicker) rootView.findViewById(R.id.datePicker); acceptButton = (Button) rootView.findViewById(R.id.buttonAccept); acceptButton.setOnClickListener(this); if (isDateSetted) { datePicker.updateDate(year, month, day); } return rootView; } @Override public void onClick(View v) { switch(v.getId()){ case R.id.buttonAccept: int year = datePicker.getYear(); int month = datePicker.getMonth() + 1; // 个月从0开始 int day = datePicker.getDayOfMonth(); listener.onDateSelected(year, month, day); break; } this.dismiss(); } @Override public void onAttach(Context context) { super.onAttach(context); listener = (DateListener) context; } public void setDate(int year, int month, int day) { this.year= year; this.month= month; this.day= day; this.isDateSetted= true; } }
活动调用对话框:
public class MainActivity extends AppCompatActivity implements ChooseDate.DateListener{ private int year; private int month; private int day; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); private void showDateDialog(); } private void showDateDialog(){ ChooseDate pickDialog = new ChooseDate(); // 我们可以设定一个日期 // pickDialog.setDate(23,10,2016); pickDialog.show(getFragmentManager(), ""); } @Override onDateSelected(int year, int month, int day){ this.day= day; this.month= month; this.year= year; } }