public class Ch4_TimePickerActivity extends AppCompatActivity implements TimePickerDialog.OnTimeSetListener {
private TextView tv_time;
private TimePicker tp_time;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_time_picker_ch4);
tv_time = findViewById(R.id.tv_time);
tp_time = findViewById(R.id.tp_time);
findViewById(R.id.btn_time).setOnClickListener(v -> {
Calendar calendar = Calendar.getInstance();
TimePickerDialog dialog = new TimePickerDialog(this, this,
calendar.get(Calendar.HOUR_OF_DAY),
calendar.get(Calendar.MINUTE),
true);
dialog.show();
});
findViewById(R.id.btn_ok).setOnClickListener(v -> {
String desc = String.format("您选择的时间是%d时%d分",
tp_time.getCurrentHour(), tp_time.getCurrentMinute());
tv_time.setText(desc);
});
}
@Override
public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
String desc = String.format("您选择的时间是%d时%d分", hourOfDay, minute);
tv_time.setText(desc);
}
}
界面
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<Button
android:id="@+id/btn_time"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="请选择时间"
android:textColor="@color/black"
android:textSize="17sp" />
<TimePicker
android:id="@+id/tp_time"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:calendarViewShown="false"
android:timePickerMode="spinner"
android:gravity="center"
android:spinnersShown="true" />
<Button
android:id="@+id/btn_ok"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:text="确 定"
android:textColor="@color/black"
android:textSize="17sp" />
<TextView
android:id="@+id/tv_time"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingLeft="5dp"
android:textColor="@color/black"
android:textSize="17sp" />
</LinearLayout>