在按钮onClickListener()
的回调函数onClick(View view)
中获取上下文非常简单:
view.getContext()
但是我不知道如何在onClick(DialogInterface v, int buttonId)
中获取上下文,它是的onClickListener
的对话框的回调
public class MainActivity extends Activity implements android.content.DialogInterface.OnClickListener
这个是可能的吗?
发布于 2011-03-27 12:02:48
当您将DialogInterface.OnClickListener
定义为匿名类时,可以引用外部上下文。如果你在一个活动中,你可以使用MyActivity.this
作为上下文。
编辑-由于您的活动正在实现DialogInterface.OnClickListener
,因此您应该能够仅使用this
作为上下文。
发布于 2011-03-27 12:02:04
如果您的DialogInterface在MainActivity中,那么可以使用以下命令获取上下文
MainActivity.this.getActivityContext();
顺便说一下,您还可以实现DialogInterface (在您的代码示例中,您已经编写了两次实现),并且可以使用相同的语句来获取活动上下文。
发布于 2014-02-27 02:23:37
下面是你是如何做的,以防你
简单的说,
dialogInterface
对象并将其强制转换为Dialog
object getContext()
使用DialogInterface.OnClickListener的示例
DialogInterface.OnClickListener foo = new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int which) {
Dialog dialog = (Dialog) dialogInterface;
Context context = dialog.getContext();
// do some work with context
}
};
这也适用于以下接口,只需使用第一个参数DialogInterface dialogInterface
和cast即可。
https://stackoverflow.com/questions/5447092
复制相似问题