activity_main.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_gravity="center"
android:text="hello world"
android:id="@+id/tv"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
<TimePicker
android:layout_gravity="center"
android:layout_marginTop="50dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
<Button
android:layout_gravity="center"
android:text="按钮"
android:id="@+id/bt"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
</LinearLayout>
MainActivity.java
package com.easybooks.myapplication;
import androidx.appcompat.app.AppCompatActivity;
import android.app.AlertDialog;
import android.app.TimePickerDialog;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.TimePicker;
import java.util.Calendar;
public class MainActivity extends AppCompatActivity {
private TextView textView;
private Button button;
private String desc;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = findViewById(R.id.tv);
button = findViewById(R.id.bt);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Calendar calendar=Calendar.getInstance();
TimePickerDialog dialog =new TimePickerDialog(MainActivity.this, new TimePickerDialog.OnTimeSetListener() {
@Override
public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
desc=String.format("%d %d",hourOfDay,minute);
}
},calendar.get(Calendar.HOUR_OF_DAY),calendar.get(Calendar.MINUTE),true);
dialog.show();
textView.setText(desc);
}
});
}
}
```![在这里插入图片描述](https://www.icode9.com/i/ll/?i=20210529194834116.PNG?,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3dlaXhpbl80NDk0MDAyNw==,size_16,color_FFFFFF,t_70#pic_center)