android 自定义控件 销毁,Android 自定义控件 这样子写Handler正确吗?

在写自定义控件时,IDE提示这样子写可能会发生泄漏

bVbADu0

提示可能发生泄漏的代码

private class CustomHandler extends Handler {

@Override

public void handleMessage(@NonNull Message msg) {

super.handleMessage(msg);

if (animCurrentPage < animMaxPage && animCurrentPage >= 0) {

invalidate();

if (animState == ANIM_NULL) {

return;

}

if (animState == ANIM_CHECK) {

animCurrentPage++;

} else if (animState == ANIM_UNCHECK) {

animCurrentPage--;

}

this.sendEmptyMessageDelayed(0, animDuration / animMaxPage);

Log.e("CustomHandler", "animCurrentPage:" + animCurrentPage);

} else {

if (isCheck) {

animCurrentPage = animMaxPage - 1;

} else {

animCurrentPage = -1;

}

invalidate();

animState = ANIM_NULL;

}

}

}

通过搜索引擎搜索到结果后,修改后的代码

private static class CustomHandler extends Handler {

private final WeakReference mCheckView;

CustomHandler(CheckView checkView) {

mCheckView = new WeakReference<>(checkView);

}

@Override

public void handleMessage(@NonNull Message msg) {

super.handleMessage(msg);

CheckView checkView = mCheckView.get();

if (checkView != null) {

int animCurrentPage = checkView.animCurrentPage;

int animMaxPage = checkView.animMaxPage;

int animState = checkView.animState;

if (animCurrentPage < animMaxPage && animCurrentPage >= 0) {

checkView.invalidate();

if (animState == ANIM_NULL) {

return;

}

if (animState == ANIM_CHECK) {

checkView.animCurrentPage++;

} else if (animState == ANIM_UNCHECK) {

checkView.animCurrentPage--;

}

this.sendEmptyMessageDelayed(0, checkView.animDuration / animMaxPage);

Log.e("CustomHandler", "animCurrentPage:" + animCurrentPage);

} else {

if (checkView.isCheck) {

checkView.animCurrentPage = animMaxPage - 1;

} else {

checkView.animCurrentPage = -1;

}

checkView.invalidate();

checkView.animState = ANIM_NULL;

}

}

}

}

请问一下,这样子修改后,是否就可以解决泄漏的问题呢?我通过LeakCanary检测后并没有发现什么,但是我不知道这样子写是否规范?

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值