将所选日期从DatePickerDialog复制到主页面中的Edittext框

时间:2013-11-10 15:02:46

标签: android

我正在关注this link以创建DatePickerDialog并将所选日期复制到Editext字段。但是,我无法理解如何做到这一点,就像我在onDateSet方法中所做的那样,它无法识别。如果有人帮忙的话。

MAIN XML:

<EditText
                android:id="@+id/add_datepurchased"
                android:inputType="date"
                android:onClick="showdate" />

主类:

EditText datpurchased;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_add_entry);
        // Show the Up button in the action bar.
        setupActionBar();

        datpurchased = (EditText) findViewById(R.id.add_datepurchased);
    }
public void showdate(View v) {
        DialogFragment newFragment = new DatePickerFragment();
        newFragment.show(getFragmentManager(), "datePicker");
    }

DatePickerFragment类:

public class DatePickerFragment extends DialogFragment implements DatePickerDialog.OnDateSetListener {

    @Override
    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);
    }

    public void onDateSet(DatePicker view, int year, int month, int day){
        EditText datpurchased = (EditText) findViewById(R.id.add_datepurchased); // GIVES ERROR
        datpurchased.setText(year+"-"+(month+1)+"-"+day);
    }
}

1 个答案:

答案 0 :(得分:0)

您应该在onCreate()

中初始化EditText