Search code examples
androidlistviewandroid-listfragment

How can style the ListView of a ListFragment


I want to keep these methods:

setListShown(true);
setListShownNoAnimation(true);

but if I use

onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)

to inflate the Fragment with a custom styled layout, the previous methods can't be used, and show this exception:

07-30 20:17:46.937: E/AndroidRuntime(1374): Caused by: java.lang.IllegalStateException: Can't be used with a custom content view
07-30 20:17:46.937: E/AndroidRuntime(1374):     at android.support.v4.app.ListFragment.setListShown(ListFragment.java:282)
07-30 20:17:46.937: E/AndroidRuntime(1374):     at android.support.v4.app.ListFragment.setListShown(ListFragment.java:258)

So, what possible solution can be?

EDIT:

The Fragment uses a loader to populate its ListView from a database. So that's the reason why I want to keep those methods, they're needed here:

public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
        mAdapter.swapCursor(data);  
        if (isResumed()) {
            setListShown(true);
        } else {
            setListShownNoAnimation(true);
        }
    }

The easiest solution would be to make my own code based on the ListFragment source, an also add the progress widget to the layout to show the same effect. By now, I'll delete those lines as I've been told. If I do the modification I'll paste it here.


Solution

  • Just replace the original ListView with your CustomListView Layout within the onCreateView(). Worked for me.

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        View layout = super.onCreateView(inflater, container,
                savedInstanceState);
        ListView lv = (ListView) layout.findViewById(android.R.id.list);
        ViewGroup parent = (ViewGroup) lv.getParent();
    
        // Remove ListView and add CustomView  in its place
        int lvIndex = parent.indexOfChild(lv);
        parent.removeViewAt(lvIndex);
        LinearLayout mLinearLayout = (LinearLayout) inflater.inflate(
                R.layout.custom_list, container, false);
        parent.addView(mLinearLayout, lvIndex, lv.getLayoutParams());
        return layout;
    }