日期的控件有TimePicker、DatePicker,可以通过这些控件查看在一般模式下一天的时间,以及在某种模式下的日期。
效果图如下:
首先完成布局文件,在布局文件添加一个TextView控件,一个DatePicker控件,一个TimePicker控件
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<TextView
android:id="@+id/tv"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="24sp" />
<DatePicker
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/dp"
/>
<TimePicker
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/tp"
/>
</LinearLayout>
接下来完成主要功能代码:
package com.example.timepicker;
import java.util.Calendar;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.DatePicker;
import android.widget.TextView;
import android.widget.TimePicker;
public class MainActivity extends ActionBarActivity {
private TextView tv;
private DatePicker dp;
private TimePicker tp;
private int mYear;
private int mMonth;
private int mDay;
private int mHour;
private int mMinute;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Calendar c = Calendar.getInstance();
mYear = c.get(Calendar.YEAR);
mMonth = c.get(Calendar.MONDAY);
mDay = c.get(Calendar.DAY_OF_MONTH);
mHour = c.get(Calendar.HOUR_OF_DAY);
mMinute = c.get(Calendar.MINUTE);
tv = (TextView) this.findViewById(R.id.tv);
dp = (DatePicker) this.findViewById(R.id.dp);
tp = (TimePicker) this.findViewById(R.id.tp);
showTime();
dp.init(mYear, mMonth, mDay, new DatePicker.OnDateChangedListener() {
@Override
public void onDateChanged(DatePicker view, int year, int monthOfYear,int dayOfMonth) {
mYear = year;
mMonth = monthOfYear;
mDay = dayOfMonth;
showTime();
}
});
tp.setOnTimeChangedListener(new TimePicker.OnTimeChangedListener() {
@Override
public void onTimeChanged(TimePicker view, int hourOfDay, int minute) {
mHour = hourOfDay;
mMinute = minute;
showTime();
}
});
}
private void showTime() {
StringBuilder sb = new StringBuilder();
String date = sb.append(mYear).append("/").append(mMonth).append("/").append(mDay)
.append(" ").append(formatTime(mHour)).append(":").append(formatTime(mMinute)).toString();
tv.setText(date);
}
private String formatTime(int i) {
String s = ""+i;
if(s.length() == 1){
s = "0"+s;
}
return s;
}
}
通过Calendar获取各个部分的时间,DatePicker有个函数init()可以实现数据的监听。具体参考代码,TimePicker通过setOnTimeChangedListener()设置监听事件。