DatePicker和TimePicker API< 11

时间:2014-02-13 23:13:38

标签: android datepicker timepicker

我在论坛和网络上寻找,但我无法找到解决问题的方法。 我正在使用DatePicker和Timepicker的程序。在我的程序中,我使用了Pickers(http://developer.android.com/guide/topics/ui/controls/pickers.html)的Google默认定义,每个选择器都有一个separeted类(时间和日期)。

public void showDatePickerDialog(View v) {
    DatePickerFragment newFragment = new DatePickerFragment();
    newFragment.show(getFragmentManager(), "datePicker");

}

public void onDateSet(DatePicker view, int year, int month, int day) {
    // Do something with the date chosen by the user
}

这是DatePickerFragment类:

    public class DatePickerFragment extends DialogFragment {

@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(),
            (OnDateSetListener) getActivity(), year, month, day);
}
    }

我读了一些关于支持库的内容并将我的活动更改为FragmentActivity,但是我遇到了一些错误。 我应该如何更改我的代码以在低于3.0的版本中实现它? 提前谢谢!

1 个答案:

答案 0 :(得分:0)

解决方案: 这里的问题是我使用 android.app.DialogFragment 而不是 android.support.v4 .app.Dialog.Fragment 。 所以,我将android.support.v4库导入了我的三个类(MainActivity,DatePickerFragment和TimePickerFragment。

下一步是将MainActivity类的 extends 活动更改为 FragmentActivity (更改导入语句):

public class MainActivity extends FragmentActivity implements
        DatePickerDialog.OnDateSetListener, TimePickerDialog.OnTimeSetListener {}

最后,我在两个类中为 getSupportFragmentManager()更改了 getFragmentManager()

public void showDatePickerDialog(View v) {
    DatePickerFragment newFragment = new DatePickerFragment();
    newFragment.show(getSupportFragmentManager(), "datePicker"); 
}

public void showTimePickerDialog(View v) {
    DialogFragment newFragment = new TimePickerFragment();
    newFragment.show(getSupportFragmentManager(), "timePicker");
}

最后一步是在android 2.3.3模拟器上进行测试,它运行正常。