Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ViewPager + Fragments Starting new Activities

If I have a viewpager where each page is a fragment. And some of those fragments want to start other views / activities do all those requests have to be passed to the parent activity. So for every page in the view pager all requests to start new activities and all results that need to be passed back to the fragments much go through the one single main activity. This seems like it would get messy. Is there a better way of handling this?

Thanks

like image 331
Nath5 Avatar asked Nov 29 '25 05:11

Nath5


1 Answers

So for every page in the view pager all requests to start new activities and all results that need to be passed back to the fragments much go through the one single main activity.

Since your Fragments live and die with the lifecycle of their parent Activity, yes they must use their parent to start and receive results from other Activities.

As of API 11, and in the latest support library, you can call these methods from inside your Fragments and they will be performed from their parent Activity for you.

    Intent intent = new Intent(getActivity(), SomeActivityToStart.class);
    startActivity(intent);

You can also start an Activity for result inside your Fragments.

    Intent intent = new Intent(getActivity(), SomeActivityToStart.class);
    startActivityForResult(intent, REQUEST_CODE);

And then override onActivityResult(int requestCode, int resultCode, Intent data) in your Fragment to get the result from the parent Activity.

This seems like it would get messy. Is there a better way of handling this?

Since you don't have to manage the communication between parent Activity and child Fragment yourself, this shouldn't be too messy in my opinion.

Checkout http://developer.android.com/reference/android/app/Fragment.html for a reference on those methods.

like image 93
Steven Byle Avatar answered Nov 30 '25 23:11

Steven Byle



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!