android TimePicker 24小时 代码
时间: 2024-09-17 20:02:15 浏览: 51
Android开发之TimePicker控件用法实例详解
要在Android的`TimePicker`中设置24小时模式,你需要在创建并初始化`TimePicker`实例时指定`hourFormat`属性为`HOUR_FORMAT_24`. 这里是一个简单的例子:
首先,在XML布局文件中,添加`TimePicker`组件如之前所述:
```xml
<TimePicker
android:id="@+id/time_picker_24_hour"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:timePickerMode="spinner"
android:hourFormat="HOUR_FORMAT_24" />
```
然后,在对应的Activity或Fragment中,你可以这样做:
```java
import android.app.TimePickerDialog;
import android.os.Bundle;
import android.view.View;
import android.widget.TimePicker;
public class YourActivity extends AppCompatActivity {
private TimePicker timePicker;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_your_layout);
timePicker = findViewById(R.id.time_picker_24_hour);
timePicker.setOnTimeChangedListener(new TimePicker.OnTimeChangedListener() {
@Override
public void onTimeChanged(TimePicker view, int hourOfDay, int minute) {
String timeFormat = String.format("%02d:%02d", hourOfDay, minute);
// 更新UI或者其他操作
}
});
View.OnClickListener showTimePickerButton = new View.OnClickListener() {
@Override
public void onClick(View v) {
show24HourTimePicker();
}
};
findViewById(R.id.show_time_button).setOnClickListener(showTimePickerButton);
}
private void show24HourTimePicker() {
final Calendar calendar = Calendar.getInstance();
int hour = calendar.get(Calendar.HOUR_OF_DAY);
int minute = calendar.get(Calendar.MINUTE);
new TimePickerDialog(YourActivity.this, new TimePickerDialog.OnTimeSetListener() {
@Override
public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
if (hourOfDay >= 0 && hourOfDay <= 23 && minute >= 0 && minute <= 59) {
timePicker.setCurrentHour(hourOfDay);
timePicker.setCurrentMinute(minute);
onTimeChanged(timePicker, hourOfDay, minute); // 更新UI
} else {
Toast.makeText(YourActivity.this, "Invalid time!", Toast.LENGTH_SHORT).show();
}
}
}, hour, minute, true).show(); // 第四个参数是是否显示AM/PM选择,这里我们设定为true(24小时模式)
}
}
```
在这个例子中,点击按钮会弹出一个24小时时间选择器,用户选择后会调用`onTimeChanged`方法更新UI。记得替换`YourActivity`和`activity_your_layout`为你实际的Activity名和布局ID。
阅读全文