[:en]Android: DatePicker[:]

[:en]DatePicker

Step 1: activity_main.xml


    

Step 2: MainActivity.java

package com.example.cambridge.datepicker;

import android.app.DatePickerDialog;
import android.app.Dialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.Toast;

import java.util.Calendar;

public class MainActivity extends AppCompatActivity {

    Button btn;
    int year_x,month_x,day_x;
    static final int DIALOG_id = 0;


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

        // Get current date
        final Calendar cal = Calendar.getInstance();
        year_x = cal.get(Calendar.YEAR);
        month_x = cal.get(Calendar.MONTH);
        day_x = cal.get(Calendar.DAY_OF_MONTH);

        showDialogOnButtonClick();
    }

    public void showDialogOnButtonClick (){
        btn = (Button)findViewById(R.id.button);

        btn.setOnClickListener(
                new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        showDialog(DIALOG_id);
                    }
                }
        );
    }

    @Override
    protected Dialog onCreateDialog(int id){
     if (id == DIALOG_id)
         return new DatePickerDialog(this, dpickerListener, year_x,month_x,day_x);
     // If doesn't match
        return null;
    }

    private  DatePickerDialog.OnDateSetListener dpickerListener
            = new DatePickerDialog.OnDateSetListener() {
        @Override
        public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
            year_x = year;
            month_x = monthOfYear + 1;
            day_x = dayOfMonth;
            Toast.makeText(MainActivity.this,year_x + "-" + month_x +"-" + day_x,Toast.LENGTH_LONG).show();

        }
    };

}

Or get the Day of Week


 // Day of week
        public void dayofweekaction () {
            Calendar sCalendar = Calendar.getInstance();
            String dayLongName = sCalendar.getDisplayName(Calendar.DAY_OF_WEEK, Calendar.LONG, Locale.getDefault());
            // Get the first three characters
            String firstthree=dayLongName.substring(0, 3);

            // Set global variable
            final globalclass globalVariable = (globalclass) getApplicationContext();
            globalVariable.setDayofweek(firstthree);

        } 

Set current date automatically

 
 // Set current date on button
        public void currentdate (){
            String currentDateTimeString = DateFormat.getDateInstance().format(new Date());
            btn.setText(currentDateTimeString);
        }

[:]

Print Friendly, PDF & Email
Scroll to Top