Search code examples
androidlistviewandroid-arrayadapterandroid-custom-viewandroid-listfragment

Add Floating Action Button to ListFragment with a custom ArrayAdapter


I used this guide to create a Custom ListView that parses its data from JSON.

https://www.bignerdranch.com/blog/customizing-android-listview-rows-subclassing/

I want to add a Floating Action Button to the ItemListFragment but don't know how.

Tried to put it under here:

public ItemView(Context context, AttributeSet attrs, int defStyle) {
    super(context, attrs, defStyle);
    LayoutInflater.from(context).inflate(R.layout.item_view_children, this, true);
    setupChildren();
}

But it gets displayed to every Item which i do not want.

Here is the code with the full example:

https://github.com/bignerdranch/android-listview-custom-view/tree/master/ListItemViewDemo/src/com/bignerdranch/android/listitemviewdemo

Any ideas how to do this?

Tried to modify inflate but dosen't work:

public static ItemView inflate(ViewGroup parent) {
    ItemView itemView = (ItemView)LayoutInflater.from(parent.getContext())
            .inflate(R.layout.item_view, parent, false);
    LayoutInflater inflater = LayoutInflater.from(parent.getContext());
    FloatingActionButton fab = (FloatingActionButton) inflater.inflate(R.layout.fab_view, parent, false);
    return itemView;
}

EDIT:

If i place it under constructor, it works ok. But Because constructor is called multiple times for each view, i have to find a way to call it only once.

public ItemView(Context context, AttributeSet attrs, int defStyle) {
    super(context, attrs, defStyle);
    LayoutInflater.from(context).inflate(R.layout.item_view_children, this, true);
    LayoutInflater.from(context).inflate(R.layout.fab_view, this, true);
    setupChildren();
}

Solution

  • Solution finally was found. Was much simpler that i thought. ItemListFragment which extends ListFragment onCreateView method invokes the overridden method.

    So replacing:

    View v = super.onCreateView(inflater, container, savedInstanceState);
    

    with:

    View v = inflater.inflate(R.layout.list_view, null); 
    

    worked!

    Also had to set list_vew.xml:

    <FrameLayout>
        <ListView android:id="@id/android:list" />
        <Button />
    </FrameLayout>