1
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

4

2 回答 2

2

试试这个它的工作代码。

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");        }
    });
}
于 2013-09-04T10:53:59.613 回答
0

Activity是一个不同的类。但这里的问题是,你不能OnDateChangedListener转换到 interface OnDateSetListener

而是尝试

new OnDateSetListener(){
    //do something here. 
};
于 2013-09-04T10:36:12.863 回答