我想通过Thread写一个简单的textview文本,但它是强制关闭
代码就是:
package thread.denemesi;
import java.util.ArrayList;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
public class baslat extends Activity {
Button buton1,buton2;
Thread thread2,thread1;
TextView yazi;
int sayi=0;
ArrayList<Integer> dizi;
int sayac=0;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
buton1=(Button)findViewById(R.id.button1);
buton2=(Button)findViewById(R.id.button2);
yazi=(TextView)findViewById(R.id.textview);
dizi=new ArrayList<Integer>();
buton1.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
thread1=new Thread(new Runnable() {
@Override
public void run() {
// for (int i = 0; i < 100; i++) {
// dizi.add(i);
// }
for (int i = 0; i < 10; i++) {
sayac++;
try {
yazi.setText("i want to write a word");
Thread.sleep(100);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
});
thread1.start();
}
});
}
答案 0 :(得分:2)
首先,您应该在Eclipse中使用adb logcat
,DDMS或DDMS透视图来检查LogCat并查看与“强制关闭”相关联的堆栈跟踪。
您会发现您的异常类似于“尝试从非UI线程修改UI”。
您需要从主应用程序线程调用setText()
,而不是后台线程。您可以通过以下方式执行此操作:
Handler
post()
上致电TextView
,传递Runnable
runOnUiThread()
上致电Activity
,传递Runnable