android 每秒自动刷新,android-每秒更新TextView

甄云
2023-12-01

android-每秒更新TextView

我环顾四周,看来到目前为止我的尝试都无济于事...

@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.deskclock);

TextView tvTime = (TextView) findViewById(R.id.tvTime);

TextView tvDate = (TextView) findViewById(R.id.tvDate);

java.util.Date noteTS = Calendar.getInstance().getTime();

String time = "hh:mm"; // 12:00

tvTime.setText(DateFormat.format(time, noteTS));

String date = "dd MMMMM yyyy"; // 01 January 2013

tvDate.setText(DateFormat.format(date, noteTS));

我基本上希望setText方法每秒更新或刷新一次,因此我的时钟实际上按应有的方式工作。 我已经看过诸如处理程序和运行之类的方法,但没有任何效果,因此,对此的任何帮助将非常感谢。 :)

9个解决方案

101 votes

在您的onCreate()方法中添加以下代码:

Thread thread = new Thread() {

@Override

public void run() {

try {

while (!thread.isInterrupted()) {

Thread.sleep(1000);

runOnUiThread(new Runnable() {

@Override

public void run() {

// update TextView here!

}

});

}

} catch (InterruptedException e) {

}

}

};

thread.start();

此代码启动一个线程,该线程每轮休眠1000毫秒。

endian answered 2020-07-11T01:07:41Z

19 votes

这是一个非常老的问题,我敢肯定那里有很多资源。 但是,将消息传播到安全的一面永远都不过分。 当前,如果其他人想要实现OP要求的功能,则可以使用:android.widget.TextClock。

TextClock文档在这里。

这是我使用的:

android:id="@+id/digitalClock"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:timeZone="GMT+0000"

android:format24Hour="dd MMM yyyy k:mm:ss"

android:format12Hour="@null"

android:textStyle="bold"

android:layout_alignParentEnd="true" />

AuroMetal answered 2020-07-11T01:08:10Z

17 votes

扩展@endian的答案,您可以使用线程并调用方法来更新TextView。 下面是我当场编写的一些代码。

java.util.Date noteTS;

String time, date;

TextView tvTime, tvDate;

@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.deskclock);

tvTime = (TextView) findViewById(R.id.tvTime);

tvDate = (TextView) findViewById(R.id.tvDate);

Thread t = new Thread() {

@Override

public void run() {

try {

while (!isInterrupted()) {

Thread.sleep(1000);

runOnUiThread(new Runnable() {

@Override

public void run() {

updateTextView();

}

});

}

} catch (InterruptedException e) {

}

}

};

t.start();

}

private void updateTextView() {

noteTS = Calendar.getInstance().getTime();

String time = "hh:mm"; // 12:00

tvTime.setText(DateFormat.format(time, noteTS));

String date = "dd MMMMM yyyy"; // 01 January 2013

tvDate.setText(DateFormat.format(date, noteTS));

}

Adam answered 2020-07-11T01:08:30Z

17 votes

如果要在textview上显示时间,最好使用Chronometer或TextClock

使用Chronometer:这是在API 1中添加的。它有很多自定义选项。

Your xml

android:id="@+id/chronometer"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:textSize="30sp" />

Your xml

Chronometer mChronometer=(Chronometer) findViewById(R.id.chronometer);

mChronometer.setBase(SystemClock.elapsedRealtime());

mChronometer.start();

使用TestClock:此小部件在API级别17中引入。我个人很喜欢Chronometer。

Your xml

android:id="@+id/textClock"

android:layout_width="fill_parent"

android:layout_height="wrap_content"

android:layout_marginTop="30dp"

android:format12Hour="hh:mm:ss a"

android:gravity="center_horizontal"

android:textColor="#d41709"

android:textSize="44sp"

android:textStyle="bold" />

就是这样,您完成了。

您可以使用这两个小部件中的任何一个。 这将使您的生活变得轻松。

Shakeeb Ayaz answered 2020-07-11T01:09:08Z

6 votes

您可以使用Timer而不是Thread。 这就是我的全部代码

package dk.tellwork.tellworklite.tabs;

import java.util.Timer;

import java.util.TimerTask;

import android.annotation.SuppressLint;

import android.app.Activity;

import android.os.Bundle;

import android.os.Handler;

import android.os.Message;

import android.view.View;

import android.view.View.OnClickListener;

import android.widget.Button;

import android.widget.TextView;

import dk.tellwork.tellworklite.MainActivity;

import dk.tellwork.tellworklite.R;

@SuppressLint("HandlerLeak")

public class HomeActivity extends Activity {

Button chooseYourAcitivity, startBtn, stopBtn;

TextView labelTimer;

int passedSenconds;

Boolean isActivityRunning = false;

Timer timer;

TimerTask timerTask;

@Override

protected void onCreate(Bundle savedInstanceState) {

// TODO Auto-generated method stub

super.onCreate(savedInstanceState);

setContentView(R.layout.tab_home);

chooseYourAcitivity = (Button) findViewById(R.id.btnChooseYourActivity);

chooseYourAcitivity.setOnClickListener(new OnClickListener() {

@Override

public void onClick(View v) {

// TODO Auto-generated method stub

//move to Activities tab

switchTabInActivity(1);

}

});

labelTimer = (TextView)findViewById(R.id.labelTime);

passedSenconds = 0;

startBtn = (Button)findViewById(R.id.startBtn);

startBtn.setOnClickListener(new OnClickListener() {

@Override

public void onClick(View v) {

// TODO Auto-generated method stub

if (isActivityRunning) {

//pause running activity

timer.cancel();

startBtn.setText(getString(R.string.homeStartBtn));

isActivityRunning = false;

} else {

reScheduleTimer();

startBtn.setText(getString(R.string.homePauseBtn));

isActivityRunning = true;

}

}

});

stopBtn = (Button)findViewById(R.id.stopBtn);

stopBtn.setOnClickListener(new OnClickListener() {

@Override

public void onClick(View v) {

// TODO Auto-generated method stub

timer.cancel();

passedSenconds = 0;

labelTimer.setText("00 : 00 : 00");

startBtn.setText(getString(R.string.homeStartBtn));

isActivityRunning = false;

}

});

}

public void reScheduleTimer(){

timer = new Timer();

timerTask = new myTimerTask();

timer.schedule(timerTask, 0, 1000);

}

private class myTimerTask extends TimerTask{

@Override

public void run() {

// TODO Auto-generated method stub

passedSenconds++;

updateLabel.sendEmptyMessage(0);

}

}

private Handler updateLabel = new Handler(){

@Override

public void handleMessage(Message msg) {

// TODO Auto-generated method stub

//super.handleMessage(msg);

int seconds = passedSenconds % 60;

int minutes = (passedSenconds / 60) % 60;

int hours = (passedSenconds / 3600);

labelTimer.setText(String.format("%02d : %02d : %02d", hours, minutes, seconds));

}

};

public void switchTabInActivity(int indexTabToSwitchTo){

MainActivity parentActivity;

parentActivity = (MainActivity) this.getParent();

parentActivity.switchTab(indexTabToSwitchTo);

}

}

NamPham answered 2020-07-11T01:09:28Z

2 votes

该代码对我有用。

//Get Time and Date

private String getTimeMethod(String formate)

{

Date date = new Date();

SimpleDateFormat dateFormat = new SimpleDateFormat(formate);

String formattedDate= dateFormat.format(date);

return formattedDate;

}

//this method is used to refresh Time every Second

private void refreshTime() //Call this method to refresh time

{

new Timer().schedule(new TimerTask() {

@Override

public void run() {

runOnUiThread(new Runnable() {

@Override

public void run() {

txtV_Time.setText(getTimeMethod("hh:mm:ss a")); //hours,Min and Second with am/pm

txtV_Date.setText(getTimeMethod("dd-MMM-yy")); //You have to pass your DateFormate in getTimeMethod()

};

});

}

}, 0, 1000);//1000 is a Refreshing Time (1second)

}

Fra Red answered 2020-07-11T01:09:47Z

1 votes

请使用TextSwitcher(用于漂亮的文本过渡动画)和计时器。

K. Oulebsir answered 2020-07-11T01:10:07Z

1 votes

您也可以使用TimerTask。

这是一种方法

private void setTimerTask() {

long delay = 3000;

long periodToRepeat = 60 * 1000; /* 1 mint */

Timer timer = new Timer();

timer.schedule(new TimerTask() {

@Override

public void run() {

runOnUiThread(new Runnable() {

@Override

public void run() {

// do your stuff here.

}

});

}

}, 3000, 3000);

}

Khemraj answered 2020-07-11T01:10:32Z

1 votes

如果您仅使用ATimeTask这样的计时器运行会更好

Timer LAIATT = new Timer();

TimerTask LAIATTT = new TimerTask()

{

@Override

public void run()

{

LoadAccountInformationAsyncTask LAIAT = new LoadAccountInformationAsyncTask();

LAIAT.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);

}

};

LAIATT.schedule(LAIATTT, 0, 1000);

Alpha Gabriel V. Timbol answered 2020-07-11T01:10:52Z

 类似资料: