java - RunOnUiThread 不更新 TextView

标签 java android multithreading

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

相关文章:

java - 使用阻塞方法为多个客户端提供服务时的线程池

Java,获取一个类的所有变量值

android - 从android抽屉导航图标中删除左边距

android - 无法使用回收器 View 滚动数据

Python多线程程序的最大线程数

适用于 Windows 和 Mac 的 Java 安装程序

java - 在 Servlet 中使用 JAR 文件不起作用?

java - 如何复用导航条码?

asp.net - 在线程内调用存储过程以更新多个记录

java - 使用java中的多线程将值写入文件