Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 911
Carlos López Avatar asked Mar 13 '14 17:03

Carlos López


People also ask

How do I refresh a fragment from another fragment?

You can access another Fragment by its tag: // find your fragment YourFragment f = (YourFragment) getSupportFragmentManager(). findFragmentByTag("yourFragTag"); // update the list view f. updateListView();

How to update Fragment from another Fragment in Android?

Use replace() to replace an existing fragment in a container with an instance of a new fragment class that you provide. Calling replace() is equivalent to calling remove() with a fragment in a container and adding a new fragment to that same container.

Can I call activity from fragment?

Best way of calling Activity from Fragment class is that make interface in Fragment and add onItemClick() method in that interface. Now implement it to your first activity and call second activity from there.

How to attach a Fragment to an activity?

Add a fragment to an activity You can add your fragment to the activity's view hierarchy either by defining the fragment in your activity's layout file or by defining a fragment container in your activity's layout file and then programmatically adding the fragment from within your activity.


1 Answers

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;
    }
like image 61
Philipp Jahoda Avatar answered Sep 20 '22 03:09

Philipp Jahoda