How to update the ListView of a Fragment from another Fragment?

11,655

You can access another Fragment by its tag:

 // find your fragment
 YourFragment f = (YourFragment) getSupportFragmentManager().findFragmentByTag("yourFragTag");

 // update the list view
 f.updateListView(); 

The tag of your Fragment is set when it is attached to a container layout:

FragmentManager fm = getSupportFragmentManager();
fm.beginTransaction().replace(R.id.frameBuy, YourFragment.newInstance(), "yourFragTag").commit();

So when you click your Button, find the Fragment you want to refresh by its tag, and then call your refresh method.

IF you are using a ViewPager, this is how to get the Fragments tag:

   /**
     * Gets the fragment tag of a fragment at a specific position in the viewpager.
     *
     * @param pos the pos
     * @return the fragment tag
     */
    public String getFragmentTag(int pos){
        return "android:switcher:"+R.id.yourViewPagerId+":"+pos;
    }
Share:
11,655
Carlos López
Author by

Carlos López

Updated on June 13, 2022

Comments

  • Carlos López
    Carlos López almost 2 years

    How can I communicate a listview of a ListFragment after an event of a Fragment inside another Fragment?

    In the ListFragment (fragment A) I have a method to refresh the ListView. But also, I need to refresh it after a click of a Button inside a Fragment, wich is child of another Fragment (fragment b)

    Its like Fragment A (listFragment) | Fragment B (detailview) (fragment C - child fragment of B)

    How can I do it?