
android里如何在子线程中如何更新主线程的控件
展开全部
步骤:
1、创建Handler对象(此处创建于主线程中便于更新UI)。
2、构建Runnable对象,在Runnable中更新界面。
3、在子线程的run方法中向UI线程post,runnable对象来更新UI。
代码
import android.os.Bundle;
import android.os.Handler;
import android.os.SystemClock;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
import android.view.SurfaceHolder;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends Activity {
private Button button;
private TextView textview;
private final int SPLASH_DISPLAY_LENGHT = 1;
private static int flag = 0;
private static int count=0;
private int ab=1;
private boolean isrun = true;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button = (Button)findViewById(R.id.button1);
textview = (TextView)findViewById(R.id.textView1);
final Handler handler= new Handler();
final Runnable runnable = new Runnable() {
public void run() {
textview.setText(Integer.toString(ab));
}
};
final Thread t = new Thread(){
//public boolean isrun=true;
@Override
public void run() {
while(isrun)
{
handler.post(runnable); //加入到消息队列 这样没有启动新的线程,虽然没有报异常。但仍然阻塞ProgressDialog的显示
ab++;
try {
sleep(1000); //直接调用
} catch (InterruptedException e) {
return;
}
}
}
};
t.start();
button.setOnClickListener(new Button.OnClickListener()
{
@Override
public void onClick(View view)
{
isrun=false;
}
});
}
}
1、创建Handler对象(此处创建于主线程中便于更新UI)。
2、构建Runnable对象,在Runnable中更新界面。
3、在子线程的run方法中向UI线程post,runnable对象来更新UI。
代码
import android.os.Bundle;
import android.os.Handler;
import android.os.SystemClock;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
import android.view.SurfaceHolder;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends Activity {
private Button button;
private TextView textview;
private final int SPLASH_DISPLAY_LENGHT = 1;
private static int flag = 0;
private static int count=0;
private int ab=1;
private boolean isrun = true;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button = (Button)findViewById(R.id.button1);
textview = (TextView)findViewById(R.id.textView1);
final Handler handler= new Handler();
final Runnable runnable = new Runnable() {
public void run() {
textview.setText(Integer.toString(ab));
}
};
final Thread t = new Thread(){
//public boolean isrun=true;
@Override
public void run() {
while(isrun)
{
handler.post(runnable); //加入到消息队列 这样没有启动新的线程,虽然没有报异常。但仍然阻塞ProgressDialog的显示
ab++;
try {
sleep(1000); //直接调用
} catch (InterruptedException e) {
return;
}
}
}
};
t.start();
button.setOnClickListener(new Button.OnClickListener()
{
@Override
public void onClick(View view)
{
isrun=false;
}
});
}
}
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询