Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
620 views
in Technique[技术] by (71.8m points)

android - 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);
    }
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...