Getting variable reference from fragment to activi

2019-01-28 21:10发布

问题:

I have an activity (MainActivity) that holds a Fragment (FragmentA) with an ArrayList<Uri> array_list = new ArrayList<Uri>();. How can my MainActivity get a reference of that array_list?

Now if you ask me why'd I want to get a reference of a variable of a fragment to an activity that holds that fragment, I'd say, I'm planning to get the items in array_list when I click the action button on my MainActivity.

I'm using ViewPager. I don't have fragment id's.

回答1:

Here is a good tuto :

Define an Interface then implement it in the activity

To allow a Fragment to communicate up to its Activity, you can define an interface in the Fragment class and implement it within the Activity. The Fragment captures the interface implementation during its onAttach() lifecycle method and can then call the Interface methods in order to communicate with the Activity.



回答2:

Probably the cleanest way you can do it is by using FragmentManager to retrieve attached fragment in an activity and then call getMyList() on that fragment to get list you want.

FragmentA fr = (FragmentA) getFragmentManager().findFragmentById(R.id.my_fragment_a_id);
if(fr != null) {   
    List<Uri> list = fr.getMyList();
    // ... do some fun stuff
}

Note that it's not a good practice to keep a reference to the fragment out of the FragmentManager due to Activity lifecycle (you end up with a reference to the fragment that has already been collected or you can prevent effective memory cleanup by GC).



回答3:

Simply make ArrayList array_list = new ArrayList(); as static variable like
public static ArrayList array_list = new ArrayList(); and call this array from your MainActivity as FragmentA.array_list .

** Keep one thing remember that don't forget to clear this array whenever items in this array are added