我试图创建一个简单的线程,在一段时间后更改textview

时间:2011-08-11 21:31:21

标签: android multithreading handler ui-thread

问题是当我点击第二个按钮时,我的应用程序崩溃,我不明白为什么。当我第二次碰到按钮时,再次假设相同。

感谢任何帮助。

public class main extends Activity {

    Boolean grabar = false;

    TextView texto;


    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        texto = (TextView) findViewById(R.id.texto);
        Button startbtn = (Button) findViewById(R.id.button);
        startbtn.setOnClickListener(new OnClickListener(){

            public void onClick(View v){

                    background.start();
            }
           });
    }

    Thread background = new Thread (new Runnable() {
        public void run() {

                    try {

                                         Thread.sleep(3000);
                        cambiarHandler.sendEmptyMessage(0);

                    } catch (InterruptedException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
            }  

     });

    Handler cambiarHandler = new Handler() {
        public void handleMessage(android.os.Message msg) {             

           texto.setText("ok");  

        }
    };


}

3 个答案:

答案 0 :(得分:4)

我看到的问题是线程被设计为运行一次。每次要运行它时,都需要创建一个新的线程实例。

答案 1 :(得分:0)

这可能与Android的仅允许UI线程修改UI的策略有关。

如果要从单独的线程修改UI,则应该使用ASyncTask。

见这里:

Update UI from Thread

答案 2 :(得分:0)

我不知道抛出了哪个异常。我想这是NPE抛出的。当您尝试将文本设置为TextView时。尝试在TextView方法中实例化handleMessage()

Handler cambiarHandler = new Handler() {
        public void handleMessage(android.os.Message msg) {             
           texto = (TextView) findViewById(R.id.texto);
           texto.setText("ok");  

        }
    };

在onClick方法中,每次单击按钮时都要执行此线程的新实例。

public void onClick(View v){
new Thread (new Runnable() {
        public void run() {

                    try {

                                         Thread.sleep(3000);
                        cambiarHandler.sendEmptyMessage(0);

                    } catch (InterruptedException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
            }  

     }).start();
}