android用线程设置TextView背景颜色时,程序崩溃
我用一个线程,来设置TextView的背景颜色,运行时我看见背景颜色变了,紧接着程序就崩溃了,百思不得其解,求教高手!代码如下:publicclassMainActivi...
我用一个线程,来设置TextView的背景颜色,运行时我看见背景颜色变了,紧接着程序就崩溃了,百思不得其解,求教高手!
代码如下:
public class MainActivity extends Activity {
super.onCreate(savedInstanceState);
this.setProgressBarVisibility(true);
setContentView(R.layout.main);
btn1 = (Button)findViewById(R.id.Button01);
tv1 = (TextView)findViewById(R.id.TextView01);
btn1.setOnClickListener (new OnClickListener(){
@Override
public void onClick(View v) {
Thread th = new Thread(begin);
th.start();
}
};
Runnable begin = new Runnable(){
@Override
public void run(){
try{
Thread.sleep(2000);
tv1.setBackgroundColor(Color.RED);
}
catch(InterruptedException e){}
}
};
} 展开
代码如下:
public class MainActivity extends Activity {
super.onCreate(savedInstanceState);
this.setProgressBarVisibility(true);
setContentView(R.layout.main);
btn1 = (Button)findViewById(R.id.Button01);
tv1 = (TextView)findViewById(R.id.TextView01);
btn1.setOnClickListener (new OnClickListener(){
@Override
public void onClick(View v) {
Thread th = new Thread(begin);
th.start();
}
};
Runnable begin = new Runnable(){
@Override
public void run(){
try{
Thread.sleep(2000);
tv1.setBackgroundColor(Color.RED);
}
catch(InterruptedException e){}
}
};
} 展开
1个回答
展开全部
晕,你怎么能直接在子线程内更新ui啊,应该用handler来更新控件,代码给你改一下了
Runnable begin = new Runnable(){
@Override
public void run(){
try{
Thread.sleep(2000);
Message msg = new Message();
msg.what = 100;
this.mHandler.sendMessage(msg);
}
catch(InterruptedException e){}
}
};
private Handler mHandler = new Handler() {
public void handleMessage(Message msg) {
switch (msg.what) {
case 100:
tv1.setBackgroundColor(Color.RED);
break;
}
};
Runnable begin = new Runnable(){
@Override
public void run(){
try{
Thread.sleep(2000);
Message msg = new Message();
msg.what = 100;
this.mHandler.sendMessage(msg);
}
catch(InterruptedException e){}
}
};
private Handler mHandler = new Handler() {
public void handleMessage(Message msg) {
switch (msg.what) {
case 100:
tv1.setBackgroundColor(Color.RED);
break;
}
};
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询