public class DatePickerDialogFragment extends DialogFragment {
    private Context context;

    public DatePickerDialogFragment(Context context) {
        this.context = context;
    }

    public Dialog onCreateDialog(Bundle savedInstanceState) {
        final Calendar c = Calendar.getInstance();
        return new DatePickerDialog(context, (OnDateSetListener) context,
                c.get(Calendar.YEAR), c.get(Calendar.MONTH),
                c.get(Calendar.DAY_OF_MONTH));
    }
}

    public class mActivity extends SherlockFragmentActivity implements
            OnDateSetListener {
        dateField.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            android.support.v4.app.FragmentManager fm = getSupportFragmentManager();
            DialogFragment newFragment = new DatePickerDialogFragment(mActivity.this);
            newFragment.show(fm, "date_frag");
        }
    });
    }


无法将Context(of Activity which impletements OnDateChangedListener)强制转换为OnDateSetListener。

最佳答案

只需尝试使用它的工作代码即可。

public static class DatePickerFragment extends DialogFragment implements
            DatePickerDialog.OnDateSetListener {
    private int year, month, day;
    private Button btn;

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

        this.year = year;
        this.month = monthOfYear;
        this.day = dayOfMonth;

    }

    public void setObject(Button v) {
        this.btn = v;
    }

    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {

        // Use the current date as the default date in the picker
        final Calendar c = Calendar.getInstance();
        int year = c.get(Calendar.YEAR);
        int month = c.get(Calendar.MONTH);
        int day = c.get(Calendar.DAY_OF_MONTH);

        // Create a new instance of DatePickerDialog and return it
        return new DatePickerDialog(getActivity(), this, year, month, day);
    }
}

public class SubmitPost extends SherlockFragmentActivity {
dateField.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            DatePickerFragment newFragment = new DatePickerFragment();
            newFragment.setObject(v);
            newFragment.show(getSupportFragmentManager(), "datePicker");        }
    });
}

08-26 05:16