子线程更新UI:View 的 post() 和 postDelay() 方法

参考:
Android开发——实现子线程更新UI
Android多线程:实现Runnable接口使用解析

在android程序中,如果在主线程中执行耗时过长的代码会出现应用未响应的提示,所以比较耗时的任务都是放在子线程中来执行,比如说下载文件等任务。一般情况,子线程中执行耗时较长的任务,都需要进行更新UI操作。View.post()是比较便捷的一种方式,更全面的方法参看上面的文章。

View.post(Runnable)

mTextView.post(new Runnable() {
    @Override
    public void run() {
        mTextView.setText("yes, 获取到数据了!#");
        mTextView.setBackgroundColor(Color.BLUE);
    }
});

View.postDelay(Runnable , long)

Android View 都有一个postDelayed(Runnable,毫秒数),用于延迟UI操作的方法,下面的代码中就是300毫秒之后,calendar_view才显示。

private void method() {
    blur_view.setBackgroundColor(Color.BLACK);
    blur_view.postDelayed(new Runnable() {
        public void run() {
            calendar_view.setVisibility(View.GONE);
            CalendarActivity.this.finish();
        }
    }, 300);
}

5秒倒计时:

num = (TextView) findViewById(R.id.num);
num.postDelayed(new Runnable() {
    @Override
    public void run() {
        num.setText("" + index);
        index--;
        if (index == 0) {
            Intent intent = new Intent(MainActivity.this, SecondActivity.class);
            startActivity(intent);
        } else {
            num.postDelayed(this, 1000);
        }
    }
}, 1000);
posted @ 2022-03-28 06:59  汉学  阅读(560)  评论(0)    收藏  举报