我正在尝试实现一个以HH:mm:ss
格式显示当前时间的代码。我设法这样做了,但是系统时间似乎还有一段时间差。代码在Fragment中实现,如下所示。
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_alarm_list, null);
tvCurrentTime = (TextView) view.findViewById(R.id.tvCurrentTime);
tvCurrentTime.setText("H");
timeHandler.sendEmptyMessage(0);
return view;
}
Handler timeHandler = new Handler() {
public void handleMessage(Message msg) {
runClock();
timeHandler.sendEmptyMessageDelayed(0, 1000);
}
};
private void runClock() {
Calendar calendar = Calendar.getInstance();
tvCurrentTime.setText(String.format("%02d:%02d:%02d",
calendar.get(Calendar.HOUR_OF_DAY),
calendar.get(Calendar.MINUTE),
calendar.get(Calendar.SECOND)));
}
时间差似乎在0.5到1秒左右。这是我运行该代码时的屏幕截图。
答案 0 :(得分:0)
检查此代码是否正常。
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_alarm_list, null);
tvCurrentTime = (TextView) view.findViewById(R.id.tvCurrentTime);
tvCurrentTime.setText("H");
timeHandler.sendEmptyMessage(0);
return view;
}
Handler timeHandler = new Handler() {
public void handleMessage(Message msg) {
runClock();
timeHandler.sendEmptyMessageDelayed(0, 500);
}
};
private void runClock() {
Calendar calendar = Calendar.getInstance();
tvCurrentTime.setText(String.format("%02d:%02d:%02d",
Calendar.getInstance().get(Calendar.HOUR_OF_DAY),
Calendar.getInstance().get(Calendar.MINUTE),
Calendar.getInstance().get(Calendar.SECOND)));
}
答案 1 :(得分:0)
你有滞后的原因是timeHandler,因为它与系统的秒数不同步,这意味着你的计时器可以在0 - 1000毫秒的不同位置运行。使间隔更小将提高显示正确的机会,但它不会修复它,因为它取决于计时器何时启动。
您可以在处理程序上使用postAtTime在特定时段运行,例如16:02:59:001,16:03:00:001,......