Sohail Saha
Sohail Saha

Reputation: 573

How to end a Fragment from within the same Fragment after it passes some data to an Activity?

I'm making an app, and I have the following:

I have just one Activity which shows Cards in a Recycler View, and I have a Fragment that allows to edit these cards.

When the user taps on any card, the card data is sent to the Fragment, and Fragment can modify it based on user input, and then the modified data is sent back to the Activity. I want the Fragment to not display, let's say Card #1's data, if after editing Card #1, the user wants to edit Card #2, and that's why I want to end the previous fragment as soon as Card #1's data is edited, so that by the time the user taps on Card #2, there's no chance of seeing Card #1 again.

Suggest me what to do please.

Upvotes: 1

Views: 72

Answers (1)

Usman Zafer
Usman Zafer

Reputation: 1361

You can remove a fragment from within same fragment by using following code

getFragmentManager().beginTransaction()
                    .remove(ActivityFragment.this).commit();

UPDATE

Communicate with Activity from Fragment

Declare an interface in Fragment

public interface cardListener{
    void onClick (String value);
}

Also create an instance of that interface in Fragment

private cardListener listener;

Make your activity implement that interface

After implementing your interface in Activity, you get the following method in activity

@Override
    public void onClick (String value) {
    //deal with the data here
    }

Now, in your fragment, before closing the fragment,you can execute the OnClick method like that.

listener.onClick(value);
getFragmentManager().beginTransaction()
                    .remove(ActivityFragment.this).commit();

Upvotes: 1

Related Questions