0

我有一个显示当前日期的编辑文本。单击该edittext,会弹出日期选择器对话框。但是在对话框中设置日期后,它会抛出空指针异常。我在下面插入我的代码。我尝试使用 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。

4

0 回答 0