前面一篇文章(http://blog.csdn.net/jasper_success/article/details/50675651),通过计算质数这样一个例子讲解了Handler的用法,这里同样使用这个例子来讲解runOnUiThread的用法。通过这个方法可以更加简单地实现UI更新。
直接上代码
public class UIUpdateActivity extends Activity{
private EditText editText;
private TextView showText;
public static Handler uiHandler;
public static int num;
public static String result;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
editText = (EditText) findViewById(R.id.editText);
showText = (TextView) findViewById(R.id.showText);
}
public void cal(View view){
result = showText.getText().toString();
new Thread(new Runnable() {
@Override
public void run() {
//计算质数
List<Integer> numList = new ArrayList<Integer>();
outer:
for (int i = 2; i < UIUpdateActivity.num; i++) {
for (int j = 2; j < Math.sqrt(i); j++) {
if (i % j == 0) {
continue outer;
}
}
numList.add(i);
}
String result = numList.toString();
UIUpdateActivity.result = result;
//通过runOnUiThread来更新UI
UIUpdateActivity.this.runOnUiThread(new Runnable() {
@Override
public void run() {
showText.setText(UIUpdateActivity.result);
}
});
}
}).start();
}
}