DatePicker在EditText中弹出

时间:2013-10-15 15:12:34

标签: android android-datepicker

我有一个显示当前日期的edittext。点击该edittext,弹出datepicker对话框。但是在对话框中设置日期后,它会抛出nullpointer异常。我在下面插入我的代码。我尝试使用DialogFragment,因为showdialog已被折旧。任何人都可以帮助我在我的代码中出错了吗?

    import java.util.Calendar;
    import android.os.Bundle;
    import android.app.Activity;
    import android.app.DatePickerDialog;
    import android.app.Dialog;
    import android.app.DialogFragment;
    import android.view.View;
    import android.widget.DatePicker;
    import android.widget.EditText;

public class setDate extends Activity {
    @Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.datepicker);

    EditText dateValue = (EditText) findViewById(R.id.date);
    final Calendar c = Calendar.getInstance();
    int yearText = c.get(Calendar.YEAR);
    int monthText = c.get(Calendar.MONTH);
    int dayText = c.get(Calendar.DAY_OF_MONTH);

    dateValue.setText(dayText + "-" + (monthText + 1) + "-" + yearText);

}

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

}

public static class DatePickerFragment extends DialogFragment implements
        DatePickerDialog.OnDateSetListener {

    public Dialog onCreateDialog(Bundle savedInstanceState) {

        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);

        return new DatePickerDialog(getActivity(), this, year, month, day);
    }

    @Override
    public void onDateSet(DatePicker view, int year, int month, int day) {

        String a = String.valueOf(day);
        String b = String.valueOf(month + 1);
        String c = String.valueOf(year);

        View id = new Activity().findViewById(R.id.date);
        EditText dateValue = (EditText) id;
        dateValue.setText(a + "-" + b + "-" + c);

    }

}
}

由于findViewById在其当前类中未定义,因此我实例化了Activity并尝试使用findViewById。

0 个答案:

没有答案