gpt4 book ai didi

Java TimePicker 不返回正确的值

转载 作者:行者123 更新时间:2023-12-02 05:37:55 27 4
gpt4 key购买 nike

在android项目中我有这个类

package mycalories.com.jalle.mycalories;

import android.app.Dialog;
import android.app.DialogFragment;
import android.app.TimePickerDialog;
import android.os.Bundle;
import android.text.format.DateFormat;
import android.text.format.Time;
import android.widget.TimePicker;

import java.util.Calendar;

public class TimePickerFragment extends DialogFragment implements
TimePickerDialog.OnTimeSetListener {

public static interface OnTimeSetListener {
void onTimeSet(Time time);
}

private OnTimeSetListener onTimeSetListener;

@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
final Calendar c = Calendar.getInstance();
int hour = c.get(Calendar.HOUR_OF_DAY);
int minute = c.get(Calendar.MINUTE);

return new TimePickerDialog(getActivity(), this, hour, minute,
DateFormat.is24HourFormat(getActivity()));
}

public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
if (onTimeSetListener != null) {
Time newTime =new Time(hourOfDay+":"+minute+ "");
onTimeSetListener.onTimeSet(newTime);
}
}

public void setOnTimeSetListener(OnTimeSetListener onTimeSetListener) {
this.onTimeSetListener = onTimeSetListener;
}
}

应该返回选择的时间。在主要 Activity 中,我有按钮和文本字段:

Button btnTime = (Button) findViewById(R.id.btnTime);
btnTime.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
TimePickerFragment timePicker = new TimePickerFragment();
timePicker.show(getFragmentManager(), "timePicker");
timePicker.setOnTimeSetListener(new OnTimeSetListener() {

@Override
public void onTimeSet(Time time) {

// SimpleDateFormat HHMM = new SimpleDateFormat("hh:mm");

final EditText txtTime = (EditText) findViewById(R.id.txtTime);
txtTime.setText(time.toString());
}
});
}
});

选择时间后,我应该采用 hh:mm 格式,但我得到的是 19700101T00000011:55(4,0,0,0,0)(显然没有选择当前时间而是默认时间)我猜想 onTimeSet 方法不对。有什么想法吗?

还有一个问题:如何在 diff Activity 中对多个文本框使用相同的 TimePicker 类?

最佳答案

Time API 有 3 个构造函数:无参数、String 参数和其他 Time 参数。您使用的构造函数是 String 构造函数,仅接受时区作为预期值,并将日期设置为 1970 年 1 月 1 日。

public Time (String timezone)

Construct a Time object in the timezone named by the string argument "timezone". The time is initialized to Jan 1, 1970.

如果您想返回包含今天日期和所选时间的时间,请尝试将代码更改为

public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
if (onTimeSetListener != null) {
Time newTime = new Time();
newTime.setToNow();
newTime.hour = hourOfDay;
newTime.minute = minute;
onTimeSetListener.onTimeSet(newTime);
}
}

关于Java TimePicker 不返回正确的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24802986/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com