[英]Can't access Application variable from OnClickListener class
I have an OnCLick listener class in my Android app defined as below. 我的Android应用程序中有一个OnCLick侦听器类,定义如下。 I need to access an application-level variable, but the last line in this code generates this compile error: "The method getApplication() is undefined for the type OnClickListenerSelectPresetItem"
我需要访问应用程序级变量,但是此代码的最后一行会生成此编译错误:“方法OnApplicationListener类型未定义getApplication()。”
How can I access Application variables from this class? 如何从此类访问Application变量?
public class OnClickListenerSelectPresetItem implements OnClickListener {
private long glbMealId = ((MyApplication) this.getApplication()).getMealId();
The error is pretty explicit. 该错误非常明显。
this
is the listener object, not the Context executing the listener. this
是侦听器对象,而不是执行侦听器的上下文。
You should use ActivityExecutingListener.this.getApplication()
. 您应该使用
ActivityExecutingListener.this.getApplication()
。
EDIT : If your listener is not an anonymous/inner class, you need to store the Context in the listener instance : 编辑:如果您的侦听器不是匿名/内部类,则需要将上下文存储在侦听器实例中:
public class OnClickListenerSelectPresetItem implements OnClickListener {
private long glbMealId;
private Activity activity;
public OnClickListenerSelectPresetItem(Activity activity) {
this.activity = activity; // facultative, but you may need it in onClick() ...
this.glbMealId = ((MyApplication) activity.getApplication()).getMealId();
}
...
}
The this operator in your case references OnClickListenerSelectPresetItem
. 您的案例中的this运算符引用
OnClickListenerSelectPresetItem
。
Here is an example of what you're trying to do, cut-pasted from one of my projects: 这是您尝试做的一个示例,是从我的一个项目中粘贴下来的:
public class PageFragment extends Fragment {
private boolean isVisible( View view )
{
return true; // fake
}
private class OnLikeClickListener implements OnClickListener
{
private boolean isVisible = PageFragment.this.isVisible(); // <------
@Override
public void onClick(View v)
{
// Do whatever
}
}
}
OK. 好。 Finally understood what your question is all about.
终于明白了您的问题是什么。
You wanna reference your implementation of the Application
class. 您想引用
Application
类的实现。 So either: 所以:
Pass an Activity
to the constructor of OnClickListenerSelectPresetItem
as @pdegand59 suggested. 按照建议将
Activity
传递给OnClickListenerSelectPresetItem
的构造函数。
Make MyApplication a singleton, for convenience (this is what I do because I don't like passing Activities): Android Application as Singleton 为了方便起见,请将MyApplication设为单例(这是我做的,因为我不喜欢传递活动): Android Application as Singleton
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.