user3718908x100
user3718908x100

Reputation: 8509

Starting Activity With Fragment

I have a NavigationDrawerActivity called MainActivity. I have another activity that appears as a dialog over my Mainctivity called GuestActivity.

I have two fragments that open with my MainActivity; HomeFragment and RegisterFragment.

I have a button in my GuestActivity, now when that button is clicked I want the GuestActivity to close and then open my MainActivity with my RegisterFragment loaded.

Is there a way to do this and if so how? Could I please see an example?

Upvotes: 0

Views: 55

Answers (2)

Stefan
Stefan

Reputation: 2178

You have to start GuestActivity with startActivityForResult. This way you can set the result with the button click and change the fragment in the MainActivity accordingly without starting the MainActivity again.

In your MainActivity change to:

    startActivityForResult(guestIntent, 1337);

And override the onActivityResult:

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// Check which request we're responding to
if (requestCode == 1337) {
    // Make sure the request was successful
    if (resultCode == RESULT_OK) {


        // Change framgnet
    }
}
}

In the onClickListener of the button in the GuestActivity add:

setResult(Activity.RESULT_OK);
GuestActivity.this.finish(();

Upvotes: 2

Krishna Meena
Krishna Meena

Reputation: 6351

When you press button then call below :

Intent intent = new Intent(this, MainActivity.class);
intent.putExtra("start_register_fragment", true);
startActivity(intent);
finish();

Now in MainActivity onCreate method check

if(getIntent.getExtras.getBoolean("start_register_fragment")) {
//call to register fragment here
}

Upvotes: 1

Related Questions