如何从Android上的DatePicker获取值

时间:2016-06-27 08:03:25

标签: android datepicker android-datepicker android-date

我有这个DatePicker代码,我可以看到DatePicker并选择一个日期但没有任何反应。如何获取日期并使用它,可能会向用户显示? 这是我的DatePicker代码:

private EditText et_tarih;
@Override
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);
    et_tarih = (EditText) view.findViewById(R.id.et_tarih);


    if(et_tarih != null)
    {
        et_tarih.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                if(event.getAction() == MotionEvent.ACTION_UP){

                    DialogFragment newFragment = new IsActivity.DatePickerFragment();
                    newFragment.show(getFragmentManager(), "datePicker");
                    return true;
                }
                return false;
            }
        });
    }

}

2 个答案:

答案 0 :(得分:1)

选择日期代码

//         **ON Create**

    edpicker.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {

            DialogFragment newFragment = new SelectDateFragment();
            newFragment.show(getFragmentManager(), "DatePicker");

}
    });



  //In class call this

 public static class SelectDateFragment extends DialogFragment implements DatePickerDialog.OnDateSetListener {

    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        final Calendar calendar = Calendar.getInstance();
        int yy = calendar.get(Calendar.YEAR);
        int mm = calendar.get(Calendar.MONTH);
        int dd = calendar.get(Calendar.DAY_OF_MONTH);
        return new DatePickerDialog(getActivity(), this, yy, mm, dd);
    }

    public void onDateSet(DatePicker view, int yy, int mm, int dd) {
        populateSetDate(yy, mm+1, dd);
    }
    public void populateSetDate(int year, int month, int day) {


        edpicker.setText(day+"-"+month+"-"+year);
    }

}

答案 1 :(得分:1)

试试这段代码

   edpicker.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View view) {

       showDialog(Date_DIALOG_ID);}});

    // Register Date Picker Dialog Listener
private DatePickerDialog.OnDateSetListener mDateSetListener = new DatePickerDialog.OnDateSetListener(){

    //callback received when the user sets the date in the datePickerDialog
    @Override
    public void onDateSet(DatePicker view, int yearSelected, int monthOfYear, int dayOfMonth) {
        year=yearSelected;
        month=monthOfYear
        day=dayOfMonth;
        // Set the selected Date on Text
        dateText.setText(year+"-"+month+"-"+day);
    }
};

// this method automatically gets called when you call ShowDialog() method
protected Dialog onCreateDialog(int id)
{
    switch (id) {
        case Date_DIALOG_ID:
            return new DatePickerDialog(this, mDateSetListener, myear, mmonth, mday);
    }
    return null;
}