To implement a TimePicker in Android, you can use the `TimePicker` widget. Here's an example XML layout:
```xml
<TimePicker
android:id="@+id/timePicker"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
```
In your Java or Kotlin code, you can interact with the `TimePicker`:
```java
public class YourActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.your_layout);
TimePicker timePicker = findViewById(R.id.timePicker);
// If you want to use the 24-hour format, uncomment the following line:
// timePicker.setIs24HourView(true);
timePicker.setOnTimeChangedListener(new TimePicker.OnTimeChangedListener() {
@Override
public void onTimeChanged(TimePicker view, int hourOfDay, int minute) {
// Handle the selected time
String selectedTime = hourOfDay + ":" + minute;
// Do something with the selected time
}
});
}
}
```
In this example, the `TimePicker.OnTimeChangedListener` is used to listen for changes in the selected time. The `onTimeChanged` method is called when the user selects a new time. You can customize the code inside this method to perform actions based on the selected time.
Remember to replace `"your_layout"` with the actual name of your layout XML file.
Comments
Post a Comment