日期和时间
作者的设计TimePicker时,大小分布不合理,我调整宽度为match-parent高度为wrap-parent就可以了。
-
public class MainActivity extends Activity
-
{
-
// 定义5个记录当前时间的变量
-
private int year;
-
private int month;
-
private int day;
-
private int hour;
-
private int minute;
-
@Override
-
public void onCreate(Bundle savedInstanceState)
-
{
-
super.onCreate(savedInstanceState);
-
setContentView(R.layout.main);
-
DatePicker datePicker = (DatePicker)findViewById(R.id.datePicker);
-
TimePicker timePicker = (TimePicker)findViewById(R.id.timePicker);
-
// 获取当前的年、月、日、小时、分钟
-
Calendar c = Calendar.getInstance();
-
year = c.get(Calendar.YEAR);
-
month = c.get(Calendar.MONTH);
-
day = c.get(Calendar.DAY_OF_MONTH);
-
hour = c.get(Calendar.HOUR);
-
minute = c.get(Calendar.MINUTE);
-
// 初始化DatePicker组件,初始化时指定监听器
-
datePicker.init(year, month, day, new OnDateChangedListener()
-
{
-
@Override
-
public void onDateChanged(DatePicker arg0, int year
-
, int month, int day)
-
{
-
MainActivity.this.year = year;
-
MainActivity.this.month = month;
-
MainActivity.this.day = day;
-
// 显示当前日期、时间
-
showDate(year, month, day, hour, minute);
-
}
-
});
-
timePicker.setEnabled(true);
-
// 为TimePicker指定监听器
-
timePicker.setOnTimeChangedListener(new OnTimeChangedListener()
-
{
-
@Override
-
public void onTimeChanged(TimePicker view
-
, int hourOfDay, int minute)
-
{
-
MainActivity.this.hour = hourOfDay;
-
MainActivity.this.minute = minute;
-
// 显示当前日期、时间
-
showDate(year, month, day, hour, minute);
-
}
-
});
-
}
-
// 定义在EditText中显示当前日期、时间的方法
-
private void showDate(int year, int month
-
, int day, int hour, int minute)
-
{
-
EditText show = (EditText) findViewById(R.id.show);
-
show.setText("您的购买日期为:" + year + "年"
-
+ (month + 1) + "月" + day + "日 " + hour + "时" + minute + "分");
-
}
-
}
|
XML文件
-
<?xml version="1.0" encoding="utf-8"?>
-
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
-
android:orientation="vertical"
-
android:layout_width="match_parent"
-
android:layout_height="match_parent">
-
<TextView
-
android:layout_width="match_parent"
-
android:layout_height="wrap_content"
-
android:text="选择购买本书的具体时间"/>
-
<!-- 定义一个DatePicker组件 -->
-
<DatePicker android:id="@+id/datePicker"
-
android:layout_width="wrap_content"
-
android:layout_height="200dp"
-
android:layout_gravity="center_horizontal"
-
android:startYear="2000"
-
android:endYear="2016"
-
android:calendarViewShown="true"
-
android:spinnersShown="true"/>
-
<!-- 定义一个TimePicker组件 -->
-
<TimePicker android:id="@+id/timePicker"
-
android:layout_width="match_parent"
-
android:layout_height="wrap_content"
-
android:layout_gravity="center_horizontal"/>
-
<!-- 显示用户输入日期、时间的控件 -->
-
<EditText android:id="@+id/show"
-
android:layout_width="match_parent"
-
android:layout_height="wrap_content"
-
android:editable="false"
-
android:cursorVisible="false"/>
-
</LinearLayout>
|
效果