在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;
}
}
应返回所选时间。在主要活动中,我有按钮和文本字段:
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)
(显然当前时间未被选中,但默认为1)
我猜方法onTimeSet
不正确。有什么想法吗?
还有一个问题:如何在差异活动中为多个文本框使用相同的TimePicker类?
答案 0 :(得分:1)
Time
API有3个构造函数:无参数,String
参数和其他Time
参数。您正在使用的构造函数({1}}只接受时区作为预期值,并将日期设置为1970年1月1日。
公共时间(字符串时区)
在名为的时区中构造一个Time对象 字符串参数“timezone”。时间初始化为1月1日, 1970。
如果您想使用今天的日期和所选时间返回String
,请尝试将代码更改为
Time
答案 1 :(得分:1)
知道您最终希望以hh:mm
格式显示时间,使用java.util.Date
类实现您的接口方法会更容易,SimpleDateFormat
“很好”。在TimePickerFragment
课程中,更改以下内容:
public static interface OnTimeSetListener {
void onTimeSet(Date date);
}
public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
if (onTimeSetListener != null) {
Date date = new Date();
date.setHours(hourOfDay);
date.setMinutes(minute);
onTimeSetListener.onTimeSet(date);
}
}
在onClick()
方法中:
public void onClick(View v)
{
TimePickerFragment timePicker = new TimePickerFragment();
timePicker.show(getFragmentManager(), "timePicker");
timePicker.setOnTimeSetListener(new TimePickerFragment.OnTimeSetListener() {
@Override
public void onTimeSet(Date date)
{
final EditText txtTime = (EditText) findViewById(R.id. txtTime);
SimpleDateFormat HHMM = new SimpleDateFormat("hh:mm");
txtTime.setText(HHMM.format(date));
}
}
);
}