如何从android中的日期选择器获取日期?

时间:2013-03-08 09:53:02

标签: android datepicker

我正在使用DatePicker作为我的申请。我想获得我选择的日期(在DatePicker上),但它没有返回所选日期。它总是返回当前日期。如何从DatePicker获取所选日期?

任何帮助将不胜感激。

    day = pickDate.getDayOfMonth();
    month = pickDate.getMonth() + 1;
    year = pickDate.getYear();
    readAndChoose = (Button) findViewById(R.id.btnReadAndChoose);
    readAndChoose.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View arg0) {

            Context context = getApplicationContext();
            CharSequence text = "" + day + "-" + "" + month + "-" + ""
                    + year;
            int duration = Toast.LENGTH_SHORT;
            Toast toast = Toast.makeText(context, text, duration);
            toast.show();

            /*
             * Intent i = new Intent(BirthActivity.this,
             * CompassActivity.class); startActivity(i);
             */

        }

    });

我不想创建DatePicker对话框,但我想使用Android提供的DatePicker。

7 个答案:

答案 0 :(得分:3)

private DatePickerDialog.OnDateSetListener datePickerListener 
                = new DatePickerDialog.OnDateSetListener() {

        // when dialog box is closed, below method will be called.
        public void onDateSet(DatePicker view, int selectedYear,
                int selectedMonth, int selectedDay) {
            year = selectedYear;
            month = selectedMonth;
            day = selectedDay;

            // set selected date into textview
            tvDisplayDate.setText(new StringBuilder().append(month + 1)
               .append("-").append(day).append("-").append(year)
               .append(" "));

            // set selected date into datepicker also
            dpResult.init(year, month, day, null);

        }
    };

参考此链接。可能会对您有所帮助。:http://www.mkyong.com/android/android-date-picker-example/

答案 1 :(得分:2)

 public class pickerdate extends Activity {
 /** Called when the activity is first created. */
 private TextView mDateDisplay;
 private Button mPickDate;
 private int mYear;
 private int mMonth;
 private int mDay;

 static final int DATE_DIALOG_ID = 0;
 @Override
 protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);


    mDateDisplay = (TextView) findViewById(R.id.dateDisplay);
    mPickDate = (Button) findViewById(R.id.pickDate);


    mPickDate.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            showDialog(DATE_DIALOG_ID);
        }
    });


    final Calendar c = Calendar.getInstance();
    mYear = c.get(Calendar.YEAR);
    mMonth = c.get(Calendar.MONTH);
    mDay = c.get(Calendar.DAY_OF_MONTH);

    updateDisplay();
}
private void updateDisplay() {
    mDateDisplay.setText(
        new StringBuilder()
                // Month is 0 based so add 1
                .append(mMonth + 1).append("-")
                .append(mDay).append("-")
                .append(mYear).append(" "));
}
private DatePickerDialog.OnDateSetListener mDateSetListener =
    new DatePickerDialog.OnDateSetListener() {

        public void onDateSet(DatePicker view, int year, 
                              int monthOfYear, int dayOfMonth) {
            mYear = year;
            mMonth = monthOfYear;
            mDay = dayOfMonth;
            updateDisplay();
        }
    };
    @Override
    protected Dialog onCreateDialog(int id) {
        switch (id) {
        case DATE_DIALOG_ID:
            return new DatePickerDialog(this,
                        mDateSetListener,
                        mYear, mMonth, mDay);
        }
        return null;
    }
 }

主布局文件

  <?xml version="1.0" encoding="utf-8"?>
  <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
   android:layout_width="wrap_content"
   android:layout_height="wrap_content"
   android:orientation="vertical">
 <TextView android:id="@+id/dateDisplay"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text=""/>
 <Button android:id="@+id/pickDate"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Date Picker"/>
  </LinearLayout>

以上代码有效。我希望这正是你所期待的。

答案 2 :(得分:2)

有两种方法可以做到这一点:

  1. 使用init()传递DatePicker的{​​{1}}方法。

    OnDateChangedListener
  2. 点击按钮或覆盖 datePicker.init( datePicker.getYear(), datePicker.getMonth(), datePicker.getDayOfMonth(), new DatePicker.OnDateChangedListener() { @Override public void onDateChanged(DatePicker datePicker, int year, int monthOfYear, int dayOfMonth) { selectedYear = year; selectedMonth = monthOfYear; selectedDayOfMonth = dayOfMonth; Log.d(LOG_TAG, "selectedDate = " + selectedYear + "-" + selectedMonth + "-" + selectedDayOfMonth ); //TODO save or use selected value here }//end onDateChangedListener }); ,以便在采取特定操作或用户离开屏幕时获取当前选择的日期。

    onPause

答案 3 :(得分:1)

我认为这就是你需要的

// the call back received when the user "sets" the date in the dialog
private DatePickerDialog.OnDateSetListener mDateSetListener =
    new DatePickerDialog.OnDateSetListener() {
        public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
            mYear = year;
            mMonth = monthOfYear;
            mDay = dayOfMonth;

        }
};

答案 4 :(得分:0)

Dj的答案会奏效。如果您想使用日历变量来存储日期,那么

     public void onDateSet(DatePicker view, int year, int monthOfYear,
            int dayOfMonth) {
        setDate.set(year, monthOfYear, dayOfMonth);          

希望这有帮助!

答案 5 :(得分:0)

还有一个很棒的教程here,它也有源代码可供下载。

有一点需要注意,在编译源代码时,需要在javapapers代码中使SelectDateFragment类为“static”,并使populateSetDate()方法为static,我也移动了这段代码:

mEdit = (EditText)findViewById(R.id.editText1);

到onCreate()方法。之后,您就可以编译代码了。

MainActivity在编辑后最终应该如下所示:

package com.javapapers.andoiddatepicker;
import java.util.Calendar;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.FragmentActivity;
import android.view.View;
import android.widget.DatePicker;
import android.widget.EditText;

public class MainActivity extends FragmentActivity {

private static EditText mEdit;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    mEdit = (EditText) findViewById(R.id.editText1);
}

public void selectDate(View view) {
    DialogFragment newFragment = new SelectDateFragment();
    newFragment.show(getSupportFragmentManager(), "DatePicker");
}

public static void populateSetDate(int year, int month, int day) {
    mEdit.setText(month + "/" + day + "/" + year);
}

public static class SelectDateFragment extends DialogFragment implements
        DatePickerDialog.OnDateSetListener {

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

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

}

答案 6 :(得分:-1)

private void openCalendar() {
    DatePickerDialog dialog = new DatePickerDialog(getContext(), (view, year, month, dayOfMonth) -> {

        date = getDateString(year, month, dayOfMonth);

    }, mYear, mMonth, mDay);
    dialog.show();

}

private String getDateString(int year, int mMonth, int mDay) {
    Calendar calendar = Calendar.getInstance();
    calendar.set(year, mMonth, mDay);
    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
    return dateFormat.format(calendar.getTime());
}