Finish activity in dialog class

喜夏-厌秋 提交于 2019-11-28 03:01:30

问题


In my MainActivity I call

 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()?

Shortened code of my dialog:

public class myDialog extends Dialog implements OnClickListener {

    void onClick() {
        Intent menu = new Intent(getContext(), menu.class);
        getContext().startActivity(menu);
    }
}

回答1:


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...

@Override
public void onClick(View v) {

    Intent menu = new Intent(mContext, menu.class);
    mContext.startActivity(menu);
    ((Activity) mContext).finish();
}



回答2:


Firstly in your dialog class pass the context of the caller activities say MainActivit.class context

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();


来源:https://stackoverflow.com/questions/22477551/finish-activity-in-dialog-class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!