14

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);
    }
}
L3n95
  • 1,505
  • 3
  • 25
  • 49
  • Post your dialog code. – Hamid Shatu Mar 18 '14 at 11:10
  • There is no finis() if I say MainActivity in the dialog class – L3n95 Mar 18 '14 at 11:13
  • The dialog code is bit too long but I have: public class myDialog extends Dialog implements android.view.View.OnClickListener{} and in the onClick method I call: Intent menu = new Intent(getContext(), menu.class); getContext().startActivity(menu); and there I want to finish the MainActivity and the dialog. – L3n95 Mar 18 '14 at 11:17
  • take a look At this ! http://stackoverflow.com/questions/3393908/how-to-get-any-identifier-of-the-topmost-activity/26308339#26308339 – Mojtaba Yeganeh Oct 10 '14 at 21:35

2 Answers2

24

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();
}
Hamid Shatu
  • 9,664
  • 4
  • 30
  • 41
6

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();
Arpit Garg
  • 8,476
  • 6
  • 34
  • 59
  • How can I do this: "pass the context of the caller activities say MainActivit.class context"? – L3n95 Mar 18 '14 at 11:22
  • @Lars3n95 yes say you are using the dialog class from MainActivity then u create a constructor in dialog class with argument as Context context. Now use this context every where in class to create the dialog and finish the current activity. – Arpit Garg Mar 18 '14 at 11:25