android view强制重绘_Android之view重绘

android中实现view的更新有两组方法,一组是invalidate,另一组是postInvalidate,其中前者是在UI线程自身中使用,而后者在非UI线程中使用。

以下是我在android文档中找到的说明,

引用

public void invalidate()

Invalidate the whole view. If the view is visible, onDraw(Canvas)

will be called at some point in the future. This must be called from a

UI thread. To call from a non-UI thread, call postInvalidate().

public void postInvalidate ()

Cause an invalidate to happen on a subsequent cycle through the

event loop. Use this to invalidate the View from a non-UI thread.

google的文档的说明实在是简单,往往看了开发中都会遇到这两个问题:

1. 没有任何异常,view没能刷新。

2. android应用异常终止,打开logcat会看到这样的异常信息, Only the original thread that created a view hierarchy can touch its views。

最后,通过查文档,上网查询才知道,invalidate和postInvalidate方法需要使用android提供的handler,才能

实现重绘,而在文档的说明中却只字不提,真是简单啊。具体是在需要重绘的地方调用handler的sendMessage方法发送消息,紧接着会os会触

发handler中的handlerMessage方法,在handlerMessage方法中再调用view的invalidate或者

postInvalidate方法就能实现重绘。

下面是我分别针对invalidate方法,给出view重绘代码,仅供参考:

Java代码  

classCustomizeViewextendsWhichView {

publicCustomizeView(Context context) {

super(context);

finalHandler handler =newHandler();

newThread(newRunnable() {

@Override

publicvoidrun() {

// delay some minutes you desire.

/*try {

Thread.sleep(3000);

} catch (InterruptedException e) {

}*/

handler.post(newRunnable() {

publicvoidrun() {

concreteUpdateUI();

invalidate();

}

});

}

}).start();

}

protectedvoidconcreteUpdateUI() {

// Add concrete movement for UI updates.

// ...

}

}

或者这样实现也可以。

Java代码  

classCustomizeViewextendsTextView {

publicCustomizeView(Context context) {

super(context);

newThread(newUIUpdateThread()).start();

}

classUIUpdateThreadimplementsRunnable {

finalHandler mHandler =newHandler();

finalRunnable mUpdateResults =newRunnable() {

publicvoidrun() {

concreteUpdateUI();

invalidate();

}

};

publicvoidrun() {

// delay some minutes you desire.

/*try {

Thread.sleep(1000 * 5);

} catch (InterruptedException e) {

e.printStackTrace();

}*/

mHandler.post(mUpdateResults);

}

}

protectedvoidconcreteUpdateUI() {

// Add concrete movement for UI updates.

// ...

}

}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值