TextSwitcher没有更新
所以我有一个TextSwitcher,我想每秒钟更新它自打开活动以来的秒数。 这是我的代码
public class SecondActivity extends Activity implements ViewFactory
{
private TextSwitcher counter;
private Timer secondCounter;
int elapsedTime = 0;
@Override
public void onCreate(Bundle savedInstanceState)
{
// Create the layout
super.onCreate(savedInstanceState);
setContentView(R.layout.event);
// Timer that keeps track of elapsed time
counter = (TextSwitcher) findViewById(R.id.timeswitcher);
Animation in = AnimationUtils.loadAnimation(this,
android.R.anim.fade_in);
Animation out = AnimationUtils.loadAnimation(this,
android.R.anim.fade_out);
counter.setFactory(this);
counter.setInAnimation(in);
counter.setOutAnimation(out);
secondCounter = new Timer();
secondCounter.schedule(new TimerUpdate(), 0, 1000);
}
/**
* Updates the clock timer every second
*/
public void updateClock()
{
//Update time
elapsedTime++;
int hours = elapsedTime/360;
int minutes = elapsedTime/60;
int seconds = elapsedTime%60;
// Format the string based on the number of hours, minutes and seconds
String time = "";
if (!hours >= 10)
{
time += "0";
}
time += hours + ":";
if (!minutes >= 10)
{
time += "0";
}
time += minutes + ":";
if (!seconds >= 10)
{
time += "0";
}
time += seconds;
// Set the text to the textview
counter.setText(time);
}
private class TimerUpdate extends TimerTask
{
@Override
public void run()
{
updateClock();
}
}
@Override
public View makeView()
{
Log.d("MakeView");
TextView t = new TextView(this);
t.setTextSize(40);
return t;
}
}所以基本上,我有一个计时器,每秒钟都会添加另一秒,它们格式化我希望显示的方式,并设置TextSwitcher的文本,我认为它叫做makeView,但makeView只被调用一次,时间保持为00: 00:01。 我错过了一个步骤,我不认为这个UI对象有很好的文档记录。
谢谢,杰克
您只能在UI线程中更新UI。 所以在你的例子中你可以做这样的事情。
private Handler mHandler = new Handler() {
void handleMessage(Message msg) {
switch(msg.what) {
CASE UPDATE_TIME:
// set text to whatever, value can be put in the Message
}
}
}
并致电
mHandler.sendMessage(msg);
在TimerTask的run()方法中。
这是解决当前问题的一种解决方案,但可能有更好的方法来使用它,而不使用TimerTasks。
链接地址: http://www.djcxy.com/p/74931.html