gpt4 book ai didi

java - RunOnUiThread 不更新 TextView

转载 作者:行者123 更新时间:2023-12-01 06:56:56 25 4
gpt4 key购买 nike

我想写一个实时计数器。我尝试使用线程,但 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com