activity_main.xml
<?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=".MainActivity">
<TimePicker
android:id="@+id/timepicker"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
</TimePicker>
</RelativeLayout>
MainActivity.java
package com.example.timecount;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.TimePicker;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TimePicker tp = (TimePicker) findViewById(R.id.timepicker);
tp.setIs24HourView(true);
tp.setOnTimeChangedListener(new TimePicker.OnTimeChangedListener() {
@Override
public void onTimeChanged(TimePicker view, int hourOfDay, int minute) {
String str = hourOfDay+"时" +minute+"分";
Toast.makeText(MainActivity.this, str, Toast.LENGTH_SHORT).show();
}
});
}
}
运行结果: