Showing posts with label Android DatePicker Dialog Example. Show all posts
Showing posts with label Android DatePicker Dialog Example. Show all posts

Wednesday, September 28, 2011

Android DatePicker Dialog Example

Now we can display android datepicker dialog box in all android mobile phones.
Example for Android Datepicker Dialog :
public class ExampleApp extends Activity implements Button.OnClickListener {
    private Button b1;
    static final int DATE_DIALOG_ID = 0;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        // Adding button to the layout
        b1=(Button)findViewById(R.id.Button01);
        b1.setOnClickListener(this);
    }
    // Creating dialog
    @Override
    protected Dialog onCreateDialog(int id) {
        Calendar c = Calendar.getInstance();
        int cyear = c.get(Calendar.YEAR);
        int cmonth = c.get(Calendar.MONTH);
        int cday = c.get(Calendar.DAY_OF_MONTH);
        switch (id) {
            case DATE_DIALOG_ID:
                return new DatePickerDialog(this, mDateSetListener, cyear, cmonth, cday);
        }
        return null;
    }
    private DatePickerDialog.OnDateSetListener mDateSetListener = new DatePickerDialog.OnDateSetListener() {
        // onDateSet method
        public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
            String date_selected = String.valueOf(monthOfYear+1)+" /"
                                  +String.valueOf(dayOfMonth)+" /"
                                  +String.valueOf(year);
            Toast.makeText(ExampleApp.this, "Selected Date is ="+date_selected, Toast.LENGTH_SHORT).show();
        }
    };
    @Override
    public void onClick(View v) {
        if(v == b1)
        showDialog(DATE_DIALOG_ID);
    }
}
The output will look like