回调中使用的正确上下文 [英] Correct context to use within callbacks
问题描述
标题几乎说明了一切.如果您有一个从一个类到另一个类的回调,并且需要从需要上下文的回调中调用某个方法,那么要使用的正确上下文是什么?一个常见的例子是带有对使用它的 Activity
或 Fragment
的回调的 AsyncTask
.
The title pretty much says it all. If you have a callback from one class to another and need to call some method from within the callback that requires a context what is the correct context to use? A common example would be an AsyncTask
with a callback to the Activity
or Fragment
that used it.
我通常尽量避免使用 getApplicationContext()
但我不能使用 this
作为回调中的上下文.在这种情况下,使用更广泛的上下文是否合适?
I generally try to avoid using getApplicationContext()
but I cannot use this
as the context from within a callback. Is this a case where using a broader context is appropriate?
为了进一步澄清,我正在考虑使用 AsyncTask 和活动之间的接口的回调.一旦我进入覆盖的接口方法,我就无法从那里获取活动上下文.
To clarify further I'm thinking of a callback with an interface between an AsyncTask and an activity. Once I'm inside the overridden interface method I can't get the activities context from within there.
推荐答案
使用活动的上下文.示例:
Use the Activity's context. Example:
MyAsyncTask mat = new MyAsyncTask(this);
MyAsyncTask 构造函数:
MyAsyncTask contructor:
public MyAsyncTask(MyActivity context) {
mContext = context;
}
从 MyAsyncTask
中调用 MyActivity 的方法 methodToCall()
:
To call MyActivity's method methodToCall()
from within MyAsyncTask
:
((MyActivity)mContext).methodToCall();
编辑 1:
我猜你的问题是这样的:
I am guessing your problem is this:
public class MyActivity extends Activity {
Button b;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.some_layout);
b = (Button) findViewById(...);
b.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Button newButton = new Button(this); // Won't work!!
}
});
}
}
解决方法:
在 MyActivity 中声明一个方法:
getContext()
public Context getContext() {
return (Context)this;
}
b.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Button newButton = new Button(getContext()); // Will work
}
});
使用MyActivity.this
代替this
.
另一种方式是声明 MyActivity 实现了接口:
Another way is to state that MyActivity implements the interface:
public class MyActivity extends Activity implements View.OnClickListener {
....
....
@Override
public void onClick(View v) {
Button newButton = Button (this) // Will Work
}
}
这篇关于回调中使用的正确上下文的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!