更正上下文以在回调中使用 [英] Correct context to use within callbacks
问题描述
标题几乎说明了一切.如果您有一个从一个类到另一个类的回调,并且需要从该回调中调用某个需要上下文的方法,那么要使用的正确上下文是什么?一个常见的示例是 AsyncTask
,该回调具有对使用它的 Activity
或 Fragment
的回调.
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();
我猜你的问题是这样的:
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屋!