I have one main activity with 2 fragments. Both fragments have a ListView
. I want to update the list in MainActivity
. Is there any way to access fragment list adapter in activity with out making adapter as static adapter.
Currently I am doing like this in Mainactivity.java
public void updatelist() {
if(fragmentstate=0)
Fragment1.adapter.notifyDataSetChanged();
else
Fragment2.adapter.notifyDataSetChanged();
}
Yes. Design guidelines for
Fragments
allow them to exposepublic
methods which can be called from theActivity
they're attached to. Simply create a method in eachFragment
and call whichever one you need to.The
Activity
should be holding references to anyFragments
it has created. Just have theFragment
methods update their own adapters.You could do the following with Otto event bus:
And a revised version of the Singleton Bus
If you just want to update lists on fragments, you don't have to access the adpaters. You can register local broadcast on fragments, and send local broadcast message from MainActivity.
From frgments,
From MainActivity,
Don't use the static adapter. There are better (safer) ways to access your fragments from it's parent
Activity
.I'm assuming you add your fragment dynamically by using something like this:
And same for fragment two.
In order to have a reference to those
Fragment
you need to add a tag when you create them. Very simple, just add one line to your existing code:And then whenever you want to get your fragment do this:
That's it