通過使用DatePickerDialog可以快速做到選擇日期的功能,除了日期以外也有時間的選擇,通過使用TimePickerDialog便能夠如同DatePickerDialog一樣輕易的做出選擇時間的功能。
layout一樣沿用昨天的部分,分別有顯示主題、時間的文字方塊與產生TimePickerDialog的按鈕。
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center_horizontal"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:textSize="20dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="50dp"
android:text="DatePickerDialog"
/>
<TextView
android:id="@+id/my_date"
android:layout_marginTop="20dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<Button
android:onClick="selectTime"
android:text="選擇時間"
android:layout_marginTop="25dp"
android:layout_width="150dp"
android:layout_height="50dp" />
</LinearLayout>
通過Calendar取得時間後便能以當下的時間來做調整,TimePickerDialog、DatePickerDialog在使用上非常相似。
public class MainActivity extends AppCompatActivity {
private int year,month,day,hour,min;
private TextView dateTextView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
dateTextView=findViewById(R.id.my_date);
}
public void selectTime(View view) {
Calendar calendar=Calendar.getInstance();
hour = calendar.get(Calendar.HOUR_OF_DAY);
min = calendar.get(Calendar.MINUTE);
new TimePickerDialog(MainActivity.this, new TimePickerDialog.OnTimeSetListener() {
@Override
public void onTimeSet(TimePicker timePicker, int i, int i1) {
String format = hour +":"+ min;
dateTextView.setText(format);
}
}, hour, min, false).show();
}
}
最後與DatePickerDialog一樣,也能通過style來快速調整顏色在@android:color/holo_green_dark下按住ctrl+左鍵能查看到可選擇的顏色。
<style name="DialogTheme" parent="Theme.AppCompat.Light.Dialog">
<item name="colorAccent">@android:color/holo_green_dark</item>
</style>
public void selectTime(View view) {
Calendar calendar=Calendar.getInstance();
hour = calendar.get(Calendar.HOUR_OF_DAY);
min = calendar.get(Calendar.MINUTE);
new TimePickerDialog(MainActivity.this,R.style.Dialog2Theme, new TimePickerDialog.OnTimeSetListener() {
@Override
public void onTimeSet(TimePicker timePicker, int i, int i1) {
String format = hour +":"+ min;
dateTextView.setText(format);
}
}, hour, min, false).show();
}