使用时钟更新TextView

编程入门 行业动态 更新时间:2024-10-11 19:20:04
本文介绍了使用时钟更新TextView的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我一直在尝试创建一个程序,该程序将输出一个有效的数字时钟,使我可以快速访问日期和时间。我有解析时间的代码,但是,更新文本视图时遇到困难。我有这个:

I have been trying to create a program that will output a working digital clock that will allow me to quickly access the date and time. I have the code to parse the time, however, I'm having difficulty updating the textview. I have this:

`public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); timer = (TextView)findViewById(R.id.timer); time = new Time(); time.setToNow(); timeString = time.toString(); changeTime = Parser(timeString); time.setToNow(); timeString = time.toString(); changeTime = Parser(timeString); timer.setText(changeTime); } private String Parser(String time){ String year = time.substring(0, 4); String month = time.substring(4,6); String day = time.substring(6, 8); String hour = time.substring(9,11); String minute = time.substring(11, 13); String second = time.substring(13, 15); String finalTime = hour + ":" + minute + ":" + second + " " + day + " " + month + " " + year; //String finalTime = second; return finalTime; }`

如何将其放入循环以不断更新textview。

How do I put this in a loop to constantly update the textview.

谢谢您能给我的帮助。

推荐答案

声明一个处理程序以更新UI线程上的TextView。

Declare a Handler to update the TextView on the UI thread.

private Handler mHandler = new Handler() { @Override public void handleMessage(Message msg) { time = new Time(); time.setToNow(); timeString = time.toString(); changeTime = Parser(timeString); timer.setText(changeTime); } };

启动一个TimeTask,它将更新您的TextView

Start a TimeTask that will update your TextView

int initialDelay = 1000; //first update in miliseconds int period = 5000; //nexts updates in miliseconds Timer timer = new Timer(); TimerTask task = new TimerTask() { public void run() { Message msg = new Message(); mHandler.sendMessage(msg); } }; timer.scheduleAtFixedRate(task, initialDelay, period);

更多推荐

使用时钟更新TextView

本文发布于:2023-11-27 14:17:29,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1638418.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:时钟   TextView

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!