1. 程式人生 > >關於DatePicker 和 TimePicker 的簡單用法

關於DatePicker 和 TimePicker 的簡單用法

初學者  android 和 Java 一共只學了一個多月  第一篇博文  自己留著筆記供以後參考 也歡迎大家指點迷津  

package com.example.try;



import java.util.Calendar;


import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.ActionBar;
import android.support.v4.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CalendarView.OnDateChangeListener;
import android.widget.DatePicker;
import android.widget.DatePicker.OnDateChangedListener;
import android.widget.TimePicker;
import android.widget.TimePicker.OnTimeChangedListener;
import android.os.Build;


public class MainActivity extends ActionBarActivity {

private DatePicker datepicker;
private TimePicker timepicker;
private Calendar calendar;
private int year;
private int month;
private int day;
private int hour;
private int minute;

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

calendar = Calendar.getInstance();
year = calendar.get(Calendar.YEAR);
month = calendar.get(Calendar.MONTH)+1;
day = calendar.get(Calendar.DAY_OF_MONTH);
hour = calendar.get(Calendar.HOUR_OF_DAY);
minute = calendar.get(Calendar.MINUTE);

setTitle(year+"-"+month+"-"+day+"-"+hour+":"+minute);
datepicker = (DatePicker) findViewById(R.id.datePicker1);
timepicker = (TimePicker) findViewById(R.id.timePicker1);
//datepicker初始化

datepicker.init(year, calendar.get(Calendar.MONTH), day, new OnDateChangedListener() {

@Override
public void onDateChanged(DatePicker arg0, int arg1, int arg2, int arg3) {
// TODO Auto-generated method stub
setTitle(arg1+"-"+(arg2+1)+"-"+arg3);
}
});


timepicker.setOnTimeChangedListener(new OnTimeChangedListener() {

@Override
public void onTimeChanged(TimePicker arg0, int arg1, int arg2) {
// TODO Auto-generated method stub
if(arg2>9)

setTitle(arg1+":"+arg2);//分鐘的話如果是小於十分鐘只會顯示類似“9”分而不是“09”分

//所以用了最笨的方法

else
setTitle(arg1+":"+0+arg2);
}
});
}






}

這個案例用了好多時間