使用 Activity 的上下文。例子:
MyAsyncTask mat = new MyAsyncTask(this);
MyAsyncTask 构造函数:
public MyAsyncTask(MyActivity context) {
mContext = context;
}
methodToCall()
从内部调用 MyActivity 的方法MyAsyncTask
:
((MyActivity)mContext).methodToCall();
编辑1:
我猜你的问题是这样的:
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 实现了接口:
public class MyActivity extends Activity implements View.OnClickListener {
....
....
@Override
public void onClick(View v) {
Button newButton = Button (this) // Will Work
}
}