简体   繁体   中英

How to create a DatePicker from class which do not extends Activity, Android?

I'm trying to create DatePicker dialog from a class that doesn't extends the Activity class. I need DatePicker in a class called EnterDate which has Context attribute containing Activity Context.

All examples of DatePicker on the WEB are basic ones written in Activity class and that's why they confusing me.

I want date picker which works good on Android lower then 3.0. I don't use XML layout.

So basically I need suggestion where to put onCreateDialog() , how to retrieve chosen time, etc.

I've Button which have onClickListener() for calling a DatePicker.

An hour ago I've asked a same question for the TimePicker and got this answer: How to create a TimePicker from class which do not extends Activity, Android?

I assume that that solution needs only minor modification to work like DatePicker..

Tnx

modified class

public class MyDatePicker {
DatePickerDialog mDatePickerDialog;


public interface onDateSet {
    public void onDate(DatePicker view, int year, int monthOfYear,
            int dayOfMonth);
}

onDateSet mOnDateSet;

public void setDateListener(onDateSet mOnDateSet) {
    this.mOnDateSet = mOnDateSet;
}
public MyDatePicker(Context ctx) {
    mDatePickerDialog = new DatePickerDialog(ctx, new OnDateSetListener() {

        @Override
        public void onDateSet(DatePicker view, int year, int monthOfYear,
                int dayOfMonth) {
            mOnDateSet.onDate(view, year, monthOfYear, dayOfMonth);

        }
    }, 2000, 1, 1);
}

public void show() {
    mDatePickerDialog.show();
}

and..

 public void ShowDatePicker() {
        MyDatePicker myTimePicker = new MyDatePicker(this);
        myTimePicker.show();
    myTimePicker.setDateListener(new onDateSet() {

        @Override
        public void onDate(DatePicker view, int year, int monthOfYear,
                int dayOfMonth) {
            Toast.makeText(MainActivity.this,
                    "date is " + year + ":" + monthOfYear+":"+dayOfMonth,
                    Toast.LENGTH_LONG).show();

        }
    });
}

You do not need activity for creating and showing dialog. You can just create Dialog with callback and init data with helper class DatePickerDialog.Builder , and then call show() for this builder.

This will work only if you are in UI thread.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM