当前位置: 代码迷 >> Android >> app中timertask()设置控件背景,总是出错
  详细解决方案

app中timertask()设置控件背景,总是出错

热度:51   发布时间:2016-04-27 22:32:54.0
app中timertask()设置控件背景,老是出错
以下做了一个按钮点击效果的程序,app刚加载时 显示图片1,点击 page3_run_page按钮 显示图片2 并1秒后变回图片1
但是点击按钮后app就报错了,不知道哪里错啦。。。请大家指点下    

ps:我把///////1注销,启用////////2来切换页面,结果没报错,成功切换

TimerTask task = new TimerTask()
{  
    public void run()
    {  
    
     page3_run_page.setBackgroundResource(R.drawable.running);    ////// 1        /图片1
    
     //intent.setClass(Main_Activity.this, Watch2_Activity.class);                ///////  2
//Main_Activity.this.startActivity(intent);



按钮点击事件   page3_run_page是一个imageButton控件
case R.id.page3_run_page:
page3_run_page.setBackgroundResource(R.drawable.running_press);    //图片2
Timer timer = new Timer();
timer.schedule(task,1000);
------解决思路----------------------
更新控件的语句必须写在UI线程中。试一下


handler.post(new Runnable()[email protected] public void run(){
    page3_run_page.setBackground...(...);
}});


其中handler就是Activity的Handler,或者


page3_run_page.post(new Runnable()[email protected] public void run(){
    page3_run_page.setBackground...(...);
}});