日期选择器,当前日期在android中

时间:2011-01-06 06:14:36

标签: android

我正在使用日期选择器,但我在日期和时间选择器方面存在一些问题。我需要日期选择器对话框显示当前日期值。同样,时间选择器应显示当前时间值。怎么做,请任何身体帮助。

Thnks。

1 个答案:

答案 0 :(得分:5)

对于DatePicker,请从Android网站查看此example

private TextView mDateDisplay;
private Button mPickDate;
private int mYear;
private int mMonth;
private int mDay;
static final int DATE_DIALOG_ID = 0;

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    // capture our View elements
    mDateDisplay = (TextView) findViewById(R.id.dateDisplay);
    mPickDate = (Button) findViewById(R.id.pickDate);

    // add a click listener to the button
    mPickDate.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            showDialog(DATE_DIALOG_ID);
        }
    });

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

    // display the current date (this method is below)
    updateDisplay();
}

// updates the date in the TextView
private void updateDisplay() {
    mDateDisplay.setText(
        new StringBuilder()
                // Month is 0 based so add 1
                .append(mMonth + 1).append("-")
                .append(mDay).append("-")
                .append(mYear).append(" "));
}

对于TimePicker,请参阅此example

private TextView mTimeDisplay;
private Button mPickTime;
private int mHour;
private int mMinute;
static final int TIME_DIALOG_ID = 0;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    // capture our View elements
    mTimeDisplay = (TextView) findViewById(R.id.timeDisplay);
    mPickTime = (Button) findViewById(R.id.pickTime);

    // add a click listener to the button
    mPickTime.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            showDialog(TIME_DIALOG_ID);
        }
    });

    // get the current time
    final Calendar c = Calendar.getInstance();
    mHour = c.get(Calendar.HOUR_OF_DAY);
    mMinute = c.get(Calendar.MINUTE);

    // display the current date
    updateDisplay();
}

// updates the time we display in the TextView
private void updateDisplay() {
    mTimeDisplay.setText(
        new StringBuilder()
            .append(pad(mHour)).append(":")
            .append(pad(mMinute)));
}

private static String pad(int c) {
    if (c >= 10)
        return String.valueOf(c);
    else
        return "0" + String.valueOf(c);
}

两个示例都显示了如何获取当前日期和时间。