简体   繁体   中英

Access fragment method from intent activity

I have a fragment, and I am starting an activity from the fragment. Now I want to call a method from the fragment in the new activity.

I tried to use interface but it seems I can't since I don't create an object of new activity in the fragment to have it call the setListener() . I am using intent to fire up the new activity.

I am not able to find how I can get fragment instance in new activity or how to call a method in the fragment. Any help would be great!

A fragment is tightly coupled with the Activity. You always need to create the Activity as the host for the fragment.

From the documentation :

A Fragment represents a behavior or a portion of user interface in an Activity. You can combine multiple fragments in a single activity to build a multi-pane UI and reuse a fragment in multiple activities. You can think of a fragment as a modular section of an activity, which has its own lifecycle, receives its own input events, and which you can add or remove while the activity is running (sort of like a "sub activity" that you can reuse in different activities).

So, you need to do the communication between Activities. An activity should not communicate with a fragment it didn't host. But it should communicate with the Activity where the fragment is hosted.

For example,
if you have two Activity which are ActivityOne and ActivityTwo. Where ActivityOne has a Fragment called ActivityOneFragment.

When you need to get the ActivityOneFragment from ActivityTwo, you need to communicate with the ActivityOne then tell it to get the ActivityOneFragment:

ActivityTwo -> ActivityOne -> ActivityOneFragment

You shouldn't do this:

ActivityTwo -> ActivityOneFragment

No, you can do not that. Because the background activity is paused/ dead. so you can not access its method.

if it is general method, you can put that method in other class. call it your utility class.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM