I'm trying to avoid updating non-visible nested fragments.
My app has three pages of nested Fragments
in a FragmentPagerAdapter
. There's a TabLayout too, if that matters. It is a network client, with a communication thread updating a database, and periodically sending updates to the UI.
To accommodate the fact that there are many fragments, each caring about different aspect(s) of the data model, each fragment implements an interface along the lines of IWantUpdatesForDataType
, and registers itself with the comm thread, thus:
class CommThread
public HashSet<IWantStatus> statusWanters = new HashSet<IWantStatus>();
interface IWantStatus {
public void updateStatus();
}
public void notifyStatusChange() {
for( IWantStatus wanter : statusWanters ) {
wanter.updateStatus();
}
}
class StatusFragment implements CommThread.IWantStatus {
@Override
onCreate() {
commThread.statusWanters.add(this);
}
@Override
updateSales() {
if( isVisible() ) {
// Update my cursor adapter, etc.
}
}
}
This is my first paged, fragmented app, so I might not have a good grasp of how the nesting works. That said, implementing StatusFragment.isVisible() was not difficult for fragments that I know will be root views in the FragmentPagerAdapter
. This answer works best of the ones I've tried.
The problem is when the StatusFragment might be a child fragment. In that case, nothing simple seems to work. Given that fragments are supposed to be self-contained and re-usable, it seems wrong to need to care about the fragment's (hypothetical) parent visibility, along the lines of this answer (which always returns true in my pager in any case).
How can the fragment determine its own visibility, while not caring whether it is a child or root fragment?