android界面刷新,Android界面刷新

至于什么invalidate,invalidate是做什么用的。

这个问题老外是这么回答的:

Each class which is derived from the View class has the invalidate and the postInvalidate method. If invalidate gets called it tells the system that the current view has changed and it should be redrawn as soon as possible. As this method can only be called from your UIThread another method is needed for when you are not in the UIThread and still want to notify the system that your View has been changed. The postInvalidate method notifies the system from a non-UIThread and the View gets redrawn in the next eventloop on the UIThread as soon as possible. It is also briefly explained in the SDK documentation.

Just compare invalidate and postInvalidate.

只要是view的子类,都会从view中继承invalidate和postInvalidate这两个方法。

当invalidate方法被调用的时候,就是在告诉系统,当前的view发生改变,应该尽可能快的来进行重绘。

这个方法仅能在UI线程中被调用。如果想要在工作线程中进行刷新界面,那么其他的方法将会被调用,这个方法就是postInvalidate方法。

这个方法将会发送消息到主线程,当主线程的消息队列轮询到当前消息的时候,这个方法会被调用。

但是需要注意的是,刷新界面并不能保证马上刷新。只是尽可能快的进行刷新。尤其是在postInvalidate方法中,这种情况会出现。

至于可能会有人问postInvalidate是怎么保证线程安全的。那么我们需要看一下postInvalidate的源码

[html

public void postInvalidate() {

postInvalidateDelayed(0);

}

public void postInvalidateDelayed(long delayMilliseconds) {

// We try only with the AttachInfo because there's no point in invalidating

// if we are not attached to our window

if (mAttachInfo != null) {

Message msg = Message.obtain();

msg.what = AttachInfo.INVALIDATE_MSG;

msg.obj = this;

mAttachInfo.mHandler.sendMessageDelayed(msg, delayMilliseconds);

}

}

public void postInvalidate() {

postInvalidateDelayed(0);

}

public void postInvalidateDelayed(long delayMilliseconds) {

// We try only with the AttachInfo because there's no point in invalidating

// if we are not attached to our window

if (mAttachInfo != null) {

Message msg = Message.obtain();

msg.what = AttachInfo.INVALIDATE_MSG;

msg.obj = this;

mAttachInfo.mHandler.sendMessageDelayed(msg, delayMilliseconds);

}

}

我们可以发现,其源码的原理依然是通过工作线程想主线程发送消息这一机制。

应该不难理解了吧。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值