xml
添加了ScrollView滚动条,但是在滚动条内部必须要有LayOut布局工具,否则会闪退
时间和日期拾取器通过DatePicker和TimePicker控件实现
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Date Time"
/>
<ScrollView
android:layout_width="match_parent"
android:layout_height="wrap_content">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<DatePicker
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/datePicker1"
>
</DatePicker>
<TimePicker
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/timePicker1"
>
</TimePicker>
</LinearLayout>
</ScrollView>
</LinearLayout>
MainActivity
package com.p3_3;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.*;
import java.util.Calendar;
public class MainActivity extends Activity {
/**
* Called when the activity is first created.
*/
Calendar calendar = Calendar.getInstance();//创建一个日历对象
int year = calendar.get(Calendar.YEAR);//获取当前年份
int month = calendar.get(Calendar.MONTH);//获取当前月份
int day = calendar.get(Calendar.DAY_OF_MONTH);//获取当前日期
int hour = calendar.get(Calendar.HOUR_OF_DAY);//获取当前小时数
int minute = calendar.get(Calendar.MINUTE);//获取当前分钟数
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
DatePicker datePicker = (DatePicker)findViewById(R.id.datePicker1);
TimePicker timePicker = (TimePicker)findViewById(R.id.timePicker1);
timePicker.setIs24HourView(true);
//初始化日期拾取器,并在初始化时指定监听器
datePicker.init(year, month, day, new DatePicker.OnDateChangedListener() {
@Override
public void onDateChanged(DatePicker datePicker, int year, int month, int day) {
MainActivity.this.year = year;
MainActivity.this.month = month;
MainActivity.this.day = day;
show(year,month,day,hour,minute);
}
});
//为日期拾取器设置监听器
timePicker.setOnTimeChangedListener(new TimePicker.OnTimeChangedListener() {
@Override
public void onTimeChanged(TimePicker timePicker, int hour, int minute) {
MainActivity.this.hour = hour;
MainActivity.this.minute = minute;
show(year,month,day,hour,minute);
}
});
}
private void show(int year,int month,int day,int hour,int minute){
String str = year + "年" + (month+1) + "月" + day + "日" + hour + ":" + minute;
//因为month是0~11,所以需+1
Toast.makeText(this,str,Toast.LENGTH_LONG);
}
}