Search code examples
androidandroid-fragmentsandroid-listfragment

How do you add an ImageView to a ListFragment?


Normally using a ListView adding images and text to the ListView items is straight forward. You create and adapter and setListAdapter(adapter) with your custom adapter.

I would like to create a Fragment app that contains the same list with ImageView. I have searched for an example but have not been able to find any that have an image. Can someone please point me to an example so I can see how it is done?

Is it done in the layout-land XML? How would you declare that using the following xml for example.

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

    <fragment class="com.demo.android.FragmentLayout$ArticleFragment"
            android:id="@+id/article" android:layout_weight="1"
            android:layout_width="0px" android:layout_height="match_parent" />

    <FrameLayout android:id="@+id/details" android:layout_weight="1"
            android:layout_width="0px" android:layout_height="match_parent"
            android:background="?android:attr/detailsElementBackground" />

</LinearLayout>

Solution

  • You just need to create a class the extends Fragment or ListFragment, then inflate the layout the contains your ListView and set your Adapter.

    Example ListFragment:

    public class Example extends ListFragment {
    
    // Adapter
    private YourListAdapter mAdapter;
    
    // ListView
    private ListView mListView;
    
    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        // Adapter
        mListView.setAdapter(mAdapter);
        super.onActivityCreated(savedInstanceState);
    }
    
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.listview, container, false);
        mListView = (ListView)view.findViewById(android.R.id.list);
        return view;
        }
    }