Harry
Harry

Reputation: 782

Inflating view for fragment before adding it to an activity

I have an activity that is switching between two fragments: one displaying a map and another displaying a list.

When the activity first starts, the map fragment is added to a FrameLayout like so:

getSupportFragmentManager()
        .beginTransaction()
        .replace(R.id.content_frame, mapFragment)
        .commit();

In which case, the second list fragment has not been inflated yet. Whenever the user browses on the map, I want the list fragment to update according to where the user pans on the map.

So basically, I want to do something like

listFragment.updateList(...);

However, since the list fragment's view hasn't been inflated yet, I can't update its views yet. Is there a way I can do this without having to wait until I add the list fragment to the FrameLayout?

Basically my end goal is for a fluid transition between fragments; when the user switches to the list view, I want the view to update as quickly as possible (which would happen if I could update the view before adding it to the activity).

Upvotes: 2

Views: 237

Answers (2)

satorikomeiji
satorikomeiji

Reputation: 469

In your list fragment have a link to Presenter which will provide data to your fragment.

public interface ListPresenter {
     public List<Object> getObjects();
}

Attach this presenter to fragment

private ListPresenter presenter;
@Override
public void onAttach(Activity activity) {
     presenter = (ListPresenter)activity;
}

Then call presenter method whenever you want to get data, it would always be available from activity.

Also add map interactor to update objects.

public interface MapInteractor {
    void setObjects(List<Object> objects);
}

In activity:

public class MyActivity extends Activity implements ListPresenter,
                                                    MapInteractor {
...
@Override
public List<Object> getObjects() {
    return currentObjects;
}

@Override
public void setObjects(List<Object> objects) {
     currentObjects = objects;
}

To instantiate your fragment quickly you can add it in hidden state at the beginning and showing it later.

getSupportFragmentManager()
    .beginTransaction()
    .add(R.id.content_frame, listFragment)
    .hide(listFragment)
    .commit();

Upvotes: 0

Kingfisher Phuoc
Kingfisher Phuoc

Reputation: 8210

I think you can store your updated list in your framgent as:

public class yourFragment extends Fragment{
      private ArrayList<Object> yourList;
}

and when you update list, you can check that if(getView() != null) -> update your ListView or set yourList = yourUpdateList. Then, in your fragment's onCreateView, check yourList is null or not, if not null, just set data to the ListView.

Upvotes: 1

Related Questions