场景
实现效果如下
注:
博客:
https://blog.csdn.net/badao_liumang_qizhi
关注公众号
霸道的程序猿
获取编程相关电子书、教程推送与免费下载。
实现
将布局改为相对布局,然后添加一个TimePicker,并添加id属性。
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout 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" tools:context=".TimePickerActivity"> <TimePicker android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/timePicker"/> </RelativeLayout>
然后来到Activity中获取时间选择器,并设置24小时制,然后设置时间改变监听器,并将改变后的时间进行输出。
package com.badao.relativelayouttest; import androidx.appcompat.app.AppCompatActivity; import android.os.Bundle; import android.widget.TimePicker; import android.widget.Toast; public class TimePickerActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_time_picker); //获取时间选择器 TimePicker timePicker = (TimePicker) findViewById(R.id.timePicker); //设置是否24小时制显示 timePicker.setIs24HourView(true); //设置时间改变监听器 timePicker.setOnTimeChangedListener(new TimePicker.OnTimeChangedListener() { @Override public void onTimeChanged(TimePicker view, int hourOfDay, int minute) { Toast.makeText(TimePickerActivity.this,hourOfDay+"时"+minute+"分",Toast.LENGTH_SHORT).show(); } }); } }