如何使用runOnUiThread [英] how to use runOnUiThread
本文介绍了如何使用runOnUiThread的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在学习做一些UI线程,所以我写了简单的测试活动。但是我想我误解的东西,因为当我点击按钮 - 应用程序是不是resposing了
公共类TestActivity延伸活动{
按钮BTN;
INT I = 0;
@覆盖
公共无效的onCreate(包savedInstanceState){
super.onCreate(savedInstanceState);
的setContentView(R.layout.main);
BTN =(按钮)findViewById(R.id.btn);
btn.setOnClickListener(新View.OnClickListener(){
@覆盖
公共无效的onClick(视图v){
runThread();
}
});
}
私人无效runThread(){
runOnUiThread(新主题(新的Runnable(){
公共无效的run(){
而(我++其中,1000){
btn.setText(#+ I);
尝试 {
视频下载(300);
}
赶上(InterruptedException异常E){
e.printStackTrace();
}
}
}
}));
}
}
解决方案
以下修正段 runThread
功能。
私人无效runThread(){
新的Thread(){
公共无效的run(){
而(我++其中,1000){
尝试 {
runOnUiThread(新的Runnable(){
@覆盖
公共无效的run(){
btn.setText(#+ I);
}
});
视频下载(300);
}赶上(InterruptedException异常E){
e.printStackTrace();
}
}
}
}。开始();
}
I'm learning to do something in UI-Thread, so I've written simple test activity. But I think I misunderstood something, because when I click on button - the app is not resposing anymore
public class TestActivity extends Activity {
Button btn;
int i = 0;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
btn = (Button)findViewById(R.id.btn);
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
runThread();
}
});
}
private void runThread(){
runOnUiThread (new Thread(new Runnable() {
public void run() {
while(i++ < 1000){
btn.setText("#"+i);
try {
Thread.sleep(300);
}
catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}));
}
}
解决方案
Below is corrected Snippet of runThread
Function.
private void runThread() {
new Thread() {
public void run() {
while (i++ < 1000) {
try {
runOnUiThread(new Runnable() {
@Override
public void run() {
btn.setText("#" + i);
}
});
Thread.sleep(300);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}.start();
}
这篇关于如何使用runOnUiThread的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文