Thursday 30 April 2015

DatePickerDialog Tutorial in android

MainActivity.class

 

public class MainActivity extends FragmentActivity
{
   Button btn_date;
    private int pYear;
    private int pMonth;
    private int pDay;
    static final int DATE_DIALOG_ID = 0;


  @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);


        final Calendar c = Calendar.getInstance();
        pYear = c.get(Calendar.YEAR);
        pMonth = c.get(Calendar.MONTH);
        pDay = c.get(Calendar.DAY_OF_MONTH);

        btn_date = (Button) findViewById(R.id.btn_date);
        btn_date.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
                showDialog(DATE_DIALOG_ID);
                  }
    });
}

@Override
    protected Dialog onCreateDialog(int id) {
        switch (id) {
            case DATE_DIALOG_ID:
                return new DatePickerDialog(this,
                        pDateSetListener,
                        pYear, pMonth, pDay);
        }
        return null;
    }

    private DatePickerDialog.OnDateSetListener pDateSetListener =
            new DatePickerDialog.OnDateSetListener() {

                public void onDateSet(DatePicker view, int year,
                                      int monthOfYear, int dayOfMonth) {

                    pYear = year;
                    pMonth = monthOfYear;
                    pDay = dayOfMonth;
                    updateDisplay();
                }
            };

    /**
     * Updates the date in the Button
     */
    private void updateDisplay() {
        btn_date.setText(
                new StringBuilder()
                        // Month is 0 based so add 1
                        .append(pMonth + 1).append("/")
                        .append(pDay).append("/")
                        .append(pYear).append(" "));
    }

}





activity_main.xml

 

<?xml version="1.0" encoding="utf-8"?>

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

  <Button
        android:layout_width="140dp"
        android:layout_height="50dp"
        android:text="Current Date"
        android:id="@+id/btn_date"
        android:background="#fff"
        android:layout_marginTop="60dp"
   />

</RelativeLayout>

No comments:

Post a Comment