gigs
gigs

Reputation: 1531

Android - determine fragment

I have an app which has one MainActivity and two Fragments. These fragments send argument to MainActivity this way:

Bundle args = new Bundle();
args.putLong("id",id);
sf.setArguments(args);

And then MainActivity takes argument in onCreate() method

protected void onCreate(Bundle savedInstanceState) {
    private long wayId = getArguments().getLong("id");
}

How can I determine which fragment sent this argument to MainActivity ?

Upvotes: 0

Views: 47

Answers (2)

Anton Pripachkin
Anton Pripachkin

Reputation: 9

You can define a separate inrterface for every fragment

public class FragmentA extends Fragment {
    public static interface FragmentAInterface {
        void doSomething(String data);
    }
}
public class FragmentB extends Fragment {
    public static interface FragmentBInterface {
        void doSomething(String data);
    }
}

And then in your activity:

    public class MyActivity extends AppCompatActivity implements FragmentA.FragmentAInterface, FragmentB.FragmentBInterface{

    @Override
    public void doSomething(String data) {
        //Guaranteed to come from Fragment A
    }

    @Override
    public void doOtherThing(String data) {
        //Guaranteed to come from Fragment B
    }
}

Upvotes: 1

br00
br00

Reputation: 1454

You can add another argument into the bundle like the tag of the fragment.

Bundle args = new Bundle();
args.putLong("id",id);
args.putString("fragmentTag", fragmentTag);
sf.setArguments(args);

and retrive the tag in your onCreate()

Upvotes: 1

Related Questions