How to use OnDateChangedListener, OnDateSetListener without using DatePickerDialog?

Zardaloop picture Zardaloop · Nov 7, 2012 · Viewed 12.2k times · Source

I want to be able to detect changes on datepicker as soon as user starts to change it. However, I don't want to use datrpickerdialog. Does anyone know why the onDateSet(DatePicker arg0, int arg1, int arg2, int arg3) doesn't fire when I change the date on datepicker?

I would highly appreciate any comment on that. Cheers

Here is the simplified version of my code:

public class AddItem extends Activity  implements OnDateChangedListener,OnDateSetListener{

DatePicker start ;

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.entryelements);
    start = (DatePicker) findViewById(R.id.start);

@Override
public void onDateChanged(DatePicker view, int year, int monthOfYear,
        int dayOfMonth) {

    // TODO Auto-generated method stub
    Toast.makeText(getApplicationContext(),
            " thiv view"+year,
            Toast.LENGTH_LONG).show();
    Log.v("indatechange", "ok");

}

@Override
public void onDateSet(DatePicker arg0, int arg1, int arg2, int arg3) {
    // TODO Auto-generated method stub
    Toast.makeText(getApplicationContext(),
            " thiv view"+arg0,
            Toast.LENGTH_LONG).show();
    Log.v("indatechange", "ok");
}

}

Answer

Sam picture Sam · Nov 9, 2012

You need to tell the DatePicker about your OnDateChangedListener. Unlike regular widgets a DatePicker does not have setOnDateChangedListener()... but it does have init(). Use init() to set the default date and declare the listener together:

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.entryelements);

    // Set the date to now
    Calendar calendar = Calendar.getInstance();
    start = (DatePicker) findViewById(R.id.start);
    start.init(calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DAY_OF_MONTH), this);
}