2013-03-18 75 views
0

timer.setText("setTextHere")在线程内不起作用。timer.setText(“setTextHere”)在线程内不起作用

Thread thread1 = new Thread(){ 

      TextView timer; 
      int t; 
      public void run(){ 
       timer=(TextView) findViewById(R.id.timer);  
       try{ 
        timer.setText("setTextHere"); 
        sleep(5000); 


       } 
       catch(Exception e){ 
        e.printStackTrace();       
       } 
       finally{ 
        Intent new1 = new Intent("com.example.app1.MENU"); 
        startActivity(new1);      
       }     
      }    
     }; 
     thread1.start(); 
+1

什么它显示前初始化的setText ??? – Subburaj 2013-03-18 09:08:58

+1

使用[Activity.runOnUiThread](http://developer.android.com/reference/android/app/Activity.html#runOnUiThread%28java.lang.Runnable%29)用于从线程 – 2013-03-18 09:09:22

+0

访问或更新UI timer =(TextView )findViewById(R.id.timer);这应该在UI线程中。您只能在UI线程上执行UI更改。 – SKK 2013-03-18 09:10:02

回答

0

在您的onCreate()地址:

h = new Handler(); 

添加这个地方:

class SetText implements Runnable { 
    public void run() { 
     // do UI task 
     timer.setText("setTextHere"); 
    } 
} 

上someFunction()修改如下:

... 
try 
{ 
    h.post(new SetText()); 
    sleep(5000); 
} 
... 
0
final TextView timer = (TextView) findViewById(R.id.timer); 
new Thread(new Runnable() { 
    public void run() { 
     try { 
      Thread.sleep(2000); 
      timer.post(new Runnable() { 
       public void run() { 
        timer.setText("setTextHere"); 
       } 
      }); 
     } catch (Exception e) { 
      e.printStackTrace(); 
     } finally { 
      Intent new1 = new Intent("com.example.app1.MENU"); 
      startActivity(new1); 
     } 
    } 
}).start(); 
2
_t = new Timer(); 
_t.scheduleAtFixedRate(new TimerTask() { 
     @Override 
     public void run() { 
      _count++; 
      runOnUiThread(new Runnable() //run on ui thread 
      { 
       public void run() 
       { 
       _tv.setText("" + _count); 
       } 
      }); 
     } 
    }, 1000, 1000); 
0

,你可以用这个和初始化线程

Thread thread1 = new Thread(){ 


     int t; 
     public void run(){  
      try{ 
       sleep(5000); 


      } 
      catch(Exception e){ 
       e.printStackTrace();       
      } 
      finally{ 
       Intent new1 = new Intent("com.example.app1.MENU"); 
       startActivity(new1);      
      }     
     }    
    }; 
    TextView timer; 
    timer=(TextView) findViewById(R.id.timer); 
    timer.setText("setTextHere"); 
    thread1.start();