Android 在对话框类中完成活动
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/22477551/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Finish activity in dialog class
提问by L3n95
In my MainActivity
I call
在我MainActivity
我叫
myDialog dialog = new myDialog(MainActivity.this);
dialog.show();
myDialog
is my own class where I customize the dialog.
In the dialog is a button. I want that the MainActivity
and the dialog finishes/dissappears when the button is pressed, because I start another Activity then.
How can I say in the myDialog
class, in the onClickListener
, that the MainActivity
should finish()
?
myDialog
是我自己的课程,我可以在其中自定义对话框。在对话框中有一个按钮。我希望MainActivity
当按下按钮时,对话框结束/消失,因为然后我启动了另一个活动。我怎么能在myDialog
课堂上说,在onClickListener
,MainActivity
应该finish()
?
Shortened code of my dialog:
我的对话框的缩短代码:
public class myDialog extends Dialog implements OnClickListener {
void onClick() {
Intent menu = new Intent(getContext(), menu.class);
getContext().startActivity(menu);
}
}
回答by Hamid Shatu
You can finish your Activity as below...
您可以按如下方式完成您的活动...
Intent intent = new Intent(context, YourSecondActivity.class);
context.startActivity(intent);
((Activity) context).finish();
Update:
更新:
In your constructor of you custom dialog class, get the activity context as below...
在您自定义对话框类的构造函数中,获取如下活动上下文...
Context mContext;
public myDialog(Context context) {
super(context);
this.mContext = context;
}
then in your onClick()
method finish the activity as below...
然后在您的onClick()
方法中完成如下活动...
@Override
public void onClick(View v) {
Intent menu = new Intent(mContext, menu.class);
mContext.startActivity(menu);
((Activity) mContext).finish();
}
回答by Arpit Garg
Firstly in your dialog class pass the context of the caller activities say MainActivit.class context
首先在你的对话类中传递调用者活动的上下文,比如 MainActivit.class上下文
Now first close the dialog
现在首先关闭对话框
//so as to avoid the window leaks as on destroying the activity it's context would also get vanished.
dialog.dismiss();
and then
进而
((Activity) context).finish();