5

I'm adding a header to my ListFragment but header doesn't appear. I tried add in onCreate and onStart but I already set my adapter. I found here this Best place to addHeaderView in ListFragment but it is not valid.

@Override

     public View onCreateView(LayoutInflater inflater, ViewGroup container,
                    Bundle savedInstanceState) {
                View v = getActivity().getLayoutInflater().inflate(R.layout.header,
                        null);
                container.addView(v,0);
                rla = new RowListAdapter(getActivity().getLayoutInflater(),
                        R.layout.itemlayout, rl);
                setListAdapter(rla);
                return super.onCreateView(inflater, container, savedInstanceState);
            }

    @Override
    public void onStart() {
        super.onStart();
        getListView().setBackgroundResource(R.color.tostadoclaro);
        getListView()
                .setDivider(getResources().getDrawable(R.drawable.divider));

        getListView().setDividerHeight(4);
    }

¡¡¡SOLUTION!!!

@Override
public void onActivityCreated(Bundle savedInstanceState) {
    View v = getActivity().getLayoutInflater().inflate(R.layout.header,
            null);
    this.getListView().addHeaderView(v);
    rla = new RowListAdapter(getActivity().getLayoutInflater(),
            R.layout.itemlayout, rl);
    setListAdapter(rla);
    super.onActivityCreated(savedInstanceState);
}
    public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState){// Empty. Use original.}
Community
  • 1
  • 1
davidpaquipalla
  • 183
  • 1
  • 2
  • 9

2 Answers2

3

Don't add the view to the container. Use addHeaderView(v).

Buffalo
  • 3,861
  • 8
  • 44
  • 69
  • I GOT IT!!! I tried tieh addHeaderView(v) but in onCreateView dind't work. I did this:@Override public void onActivityCreated(Bundle savedInstanceState) { View v = getActivity().getLayoutInflater().inflate(R.layout.header, null); this.getListView().addHeaderView(v); rla = new RowListAdapter(getActivity().getLayoutInflater(), R.layout.itemlayout, rl); setListAdapter(rla); super.onActivityCreated(savedInstanceState); } – davidpaquipalla Oct 26 '12 at 15:11
  • 1
    Glad to hear! I should have probably mentioned that too.. :) – Buffalo Oct 28 '12 at 07:21
0

The complete code (adapted from here):

@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);
    TextView tv = new TextView(getActivity());
    tv.setText("Hello");
    getListView().addHeaderView(tv);
    setListAdapter(new ArrayAdapter<String>(getActivity(), android.R.layout.simple_list_item_1,
            new String[] { "Hello world" }));
}

@Override
public void onDestroyView() {
    setListAdapter(null);
    super.onDestroyView();
}

See also: Best place to addHeaderView in ListFragment

Community
  • 1
  • 1
Felipe
  • 16,649
  • 11
  • 68
  • 92