gpt4 book ai didi

java - 如何在 handleMessage 中使用类局部非静态变量时使 android 句柄静态

转载 作者:太空狗 更新时间:2023-10-29 14:53:16 24 4
gpt4 key购买 nike

此代码 fragment 在 CircleView 扩展 View 类中

private Handler handler = new Handler()
{
@Override
public void handleMessage(Message msg)
{

super.handleMessage(msg);
if (curAng > 0 && curTime > 0) // this is non static varriable in class
{
curAng = curAng - (2 * Math.PI)/360;
}
else
{
curAng = 0; // this is non static variable in class
task.cancel(); // this is non static variable in class
}
invalidate();
}
};

我尝试了几个来自 stackoverflow 的解决方案,但对我没有任何作用。下面的例子

static class MyInnerHandler extends Handler{
WeakReference<CircleView> mFrag;

MyInnerHandler(CircleView aview) {
mFrag = new WeakReference<CircleView>(aview);
}

@Override
public void handleMessage(Message msg)
{

super.handleMessage(msg);
if (curAng > 0 && curTime > 0) // this is non static variable in class
{
curAng = curAng - (2 * Math.PI)/360;
}
else
{
curAng = 0; // this is non static variable in class
task.cancel(); // this is non static variable in class
}
invalidate();
}
}
MyInnerHandler myHandler = new MyInnerHandler(this);

问题是,如果我按照上面的代码进行操作,我会收到错误消息,无法从静态上下文中引用非静态字段。我不想将私有(private)变量更改为静态变量。请帮助谢谢。(注意:- 我还在代码中的某处使用了 handler.obtainMessage().sendToTarget();)。

最后我找到了解决方案,关于如何访问类变量而不将它们设为静态。

这是答案:-

 static class MyInnerHandler extends Handler{
WeakReference<CircleView> mFrag;

MyInnerHandler(CircleView aview) {
mFrag = new WeakReference<CircleView>(aview);
}

@Override
public void handleMessage(Message msg)
{
CircleView aview = mFrag.get(); // Here is solution. with aview. can access all method and variables.
super.handleMessage(msg);
if (aview.curAng > 0 && aview.curTime > 0) // this is non static varriable in class
{
aview.curAng = curAng - (2 * Math.PI)/360;
}
else
{
aview.curAng = 0; // this is non static variable in class
aview.task.cancel(); // this is non static variable in class
}
aview.invalidate();
}
}
MyInnerHandler myHandler = new MyInnerHandler(this);

最佳答案

我认为除了像您那样做之外,您最好在继续之前检查 aview 是否为空。因为当消息被发布到处理程序时,原始 View 可能已经消失并且有机会已经被垃圾收集。

@Override
public void handleMessage(Message msg)
{

super.handleMessage(msg);

CircleView aview = mFrag.get(); // Here is solution.
//with aview. can access all method and variables.


if (aview==null) return;

... ...
}

关于java - 如何在 handleMessage 中使用类局部非静态变量时使 android 句柄静态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33603132/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com