Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Finish activity in dialog class

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);
    }
}
like image 840
L3n95 Avatar asked Mar 18 '14 11:03

L3n95


People also ask

How do you finish an activity?

On Clicking the back button from the New Activity, the finish() method is called and the activity destroys and returns to the home screen.

How do you finish multiple activities?

When the user is on Activity D and click a button called exit, the application should go back to Activity B and finish the Activities C and D.

How do I stop dialog closing?

AlertDialog dialog = (AlertDialog) getDialog(); dialog. getButton(AlertDialog. BUTTON_POSITIVE). setEnabled(false);

How do I close dialog on Android?

You can use the methods cancel() or dismiss() . The method cancel() essentially the same as calling dismiss(), but it will also call your DialogInterface.


2 Answers

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();
}
like image 192
Hamid Shatu Avatar answered Sep 22 '22 09:09

Hamid Shatu


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();
like image 45
Arpit Garg Avatar answered Sep 24 '22 09:09

Arpit Garg