Finish activity in dialog class

2019-01-26 06:24发布

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

2条回答
祖国的老花朵
2楼-- · 2019-01-26 06:42

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();
}
查看更多
干净又极端
3楼-- · 2019-01-26 07:04

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();
查看更多
登录 后发表回答