Android Studio中点击启停按钮记录时间异常问题求助
问题分析与解决方案
嗨,我来帮你搞定这个时间记录的问题~
你遇到的核心问题是:初始化时创建的Calendar实例没有在点击按钮时更新时间,所以不管什么时候点击,获取的都是你刚加载控件那一刻的时间,自然不会变化。另外还有个小细节,你的SimpleDateFormat格式写错了——小写的mm代表分钟,月份应该用大写的MM,不然显示的“月份”其实是分钟数哦!
修正后的代码
pause = myInflatedView.findViewById(R.id.buttonpause); pause.setBackgroundResource(R.drawable.pause); showdate = myInflatedView.findViewById(R.id.textViewDate); showdate2 = myInflatedView.findViewById(R.id.textViewDate2); // 无需提前初始化Calendar,每次点击时再获取当前时间即可 simpleDateFormat = new SimpleDateFormat("dd MM yyyy HH:mm:ss"); // 修正月份格式为大写MM pause.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { // 每次点击时重新获取Calendar实例,拿到最新的当前时间 Calendar currentCalendar = Calendar.getInstance(); if (isPressed) { view.setBackgroundResource(R.drawable.pause); String currentTime = simpleDateFormat.format(currentCalendar.getTime()); showdate2.setText(currentTime); }else { view.setBackgroundResource(R.drawable.start); String currentTime = simpleDateFormat.format(currentCalendar.getTime()); showdate.setText(currentTime); } isPressed = !isPressed; } });
关键修改点说明
- 动态获取当前时间:移除了提前初始化的
calendar和calendar2,改为每次点击按钮时创建新的Calendar实例,确保拿到的是点击瞬间的真实时间。你也可以选择保留原有Calendar对象,在点击时调用calendar.setTimeInMillis(System.currentTimeMillis())来更新时间,效果是一样的。 - 修复日期格式错误:把
dd mm yyyy调整为dd MM yyyy,避免把分钟数当成月份显示。 - 简化变量逻辑:去掉了提前保存的
Date和Date2变量,每次点击直接生成时间字符串并设置到TextView,减少不必要的冗余代码。
这样修改后,不管点击启动还是暂停按钮,都会准确记录下点击那一刻的时间啦~
内容的提问来源于stack exchange,提问作者Fionnuala
相关产品推荐
相关产品推荐

