[embedyt] https://www.youtube.com/watch?v=33BFCdL0Di0[/embedyt]
activity_main.xmlDatePickerFragment.javaMainActivity.java
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context="com.example.application.datepickerexample.MainActivity"> <TextView android:id="@+id/textView" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_above="@id/button" android:layout_centerHorizontal="true" android:layout_marginBottom="28dp" android:text="date" android:textSize="30sp" /> <Button android:id="@+id/button" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerHorizontal="true" android:layout_centerVertical="true" android:text="open date picker" /> </RelativeLayout>
package com.example.application.datepickerexample; import android.app.DatePickerDialog; import android.app.Dialog; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.v4.app.DialogFragment; import java.util.Calendar; public class DatePickerFragment extends DialogFragment { @NonNull @Override public Dialog onCreateDialog(Bundle savedInstanceState) { Calendar c = Calendar.getInstance(); int year = c.get(Calendar.YEAR); int month = c.get(Calendar.MONTH); int day = c.get(Calendar.DAY_OF_MONTH); return new DatePickerDialog(getActivity(), (DatePickerDialog.OnDateSetListener) getActivity(), year, month, day); } }
package com.example.application.datepickerexample; import android.app.DatePickerDialog; import android.support.v4.app.DialogFragment; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.DatePicker; import android.widget.TextView; import java.text.DateFormat; import java.util.Calendar; public class MainActivity extends AppCompatActivity implements DatePickerDialog.OnDateSetListener { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Button button = (Button) findViewById(R.id.button); button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { DialogFragment datePicker = new DatePickerFragment(); datePicker.show(getSupportFragmentManager(), "date picker"); } }); } @Override public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) { Calendar c = Calendar.getInstance(); c.set(Calendar.YEAR, year); c.set(Calendar.MONTH, month); c.set(Calendar.DAY_OF_MONTH, dayOfMonth); String currentDateString = DateFormat.getDateInstance(DateFormat.FULL).format(c.getTime()); TextView textView = (TextView) findViewById(R.id.textView); textView.setText(currentDateString); } }