Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add a fragment as ListView header

I'm targeting an android app to API 15 and minimum 8. So I use support library to manage fragments. I have a set of fragments that I use in several parts of the app.

Now, in an activity I have a ListView in the layout:

<ListView xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/listOfEvents"
    android:layout_width="match_parent" android:layout_height="match_parent">
</ListView>

I would like to add a fragment of mine in the ListView header. I tried this:

    @Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.event_open);

    listOfEvents = (ListView) findViewById(R.id.listOfEvents);

            Fragment fragment = new SortingStandardFragment();
            getSupportFragmentManager()
              .beginTransaction()
                  .add(fragment, null)
              .commit();

            View fragmentView = fragment.getView(); // problem: fragment is null!
            listOfEvents.addHeaderView(fragmentView);
    }

but i get an error since fragment.getView() returns null (api reference docs say that I have to put a GroupView Id in the add call, but where should I put the GroupView in the layout? Is there another way to hit the mark?

like image 706
onof Avatar asked Sep 27 '12 21:09

onof


2 Answers

I solved this by creating a new layout containing just the fragment I need in the list header:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <fragment
        android:id="@+id/myFragmentEmbedded"
        android:name=".SortingStandardFragment"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

</LinearLayout>

and in the activity code:

LayoutInflater inflater = getLayoutInflater();
header = inflater.inflate(R.layout.myLayout, null);
listOfEvents.addHeaderView(header);

SortingStandardFragmenttitleFragment = (SortingStandardFragment) 
     getSupportFragmentManager()
          .findFragmentById(R.id.myFragmentEmbedded);
like image 118
onof Avatar answered Oct 04 '22 04:10

onof


I wanted a version without having to resort to yet another xml file, so here it goes:

Fragment fragment = ...
FrameLayout v = new FrameLayout(getActivity());
v.setId(42);
listView.addHeaderView(v, null, false);
FragmentManager fm = getActivity().getSupportFragmentManager();
fm.beginTransaction().add(v.getId(), fragment).commit();
like image 26
njzk2 Avatar answered Oct 04 '22 03:10

njzk2