我想写一个实时计数器。我尝试使用线程,但 android 警告我只有 Activity 线程可以接触 View 。我找到了一个使用 runOnUiThread
的解决方案,但它也不起作用
public class CounterInRealTimeExampleActivity extends Activity {
private TextView textView;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
LinearLayout layout = new LinearLayout(this);
textView = new TextView(this);
textView.setTag(new Integer(0));
layout.addView(textView);
setContentView(layout);
runOnUiThread(new Runnable() {
@Override
public void run() {
//while(true)
{
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
increment();
}
}
});
}
public void increment() {
textView.setTag(new Integer((Integer)textView.getTag())+1);
textView.setText(Integer.toString((Integer)textView.getTag()));
}
}
最佳答案
我在这里粘贴代码。这可以帮助你..
class UpdateTimeTask extends TimerTask {
public void run() {
String time = DateUtils.now("hh:mm:ss'T'a");
String[]arrValues = time.split("T");
if(arrValues.length>0) {
String strValue= arrValues[0];
String []arrTimeValues = strValue.split(":");
String strValue1= arrTimeValues[2];
setTimertext(strValue1);
}
}
public void setTimertext(String strValue) {
runOnUiThread(new Runnable() {
public void run() {
FinalTime=timer_time--;
btnTimer.setText(String.valueOf(FinalTime));
}
});
}
}
关于java - RunOnUiThread 不更新 TextView,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9750397/