1

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();
4

5 回答 5

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 ); 
于 2013-03-18T10:21:17.093 回答
1

您无法从后台线程触摸 UI。尝试使用 AsyncTask http://developer.android.com/reference/android/os/AsyncTask.html

于 2013-03-18T09:12:00.410 回答
0

您可以在初始化线程之前使用它并初始化 setText

    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();
于 2014-06-17T16:47:54.360 回答
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);
}
...
于 2013-03-18T09:28:57.333 回答
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();
于 2013-03-18T10:06:01.093 回答