Search code examples
androidandroid-listfragment

Adding different icon for each item in ListFragment


I have successfully set up a ListFragment with a simple icon next to each of the Strings/items.

Now I would like to add a different icon/image for each of the items/strings in my List.

How would I be able to accomplish this? I have done it before using a normal activity, but not using ListFragments.

Thanks in advance...

ListFragment class:

public class Fragment2 extends ListFragment {

public class MyListAdapter extends ArrayAdapter<String> {

    Context myContext;

    public MyListAdapter(Context context, int textViewResourceId,
            String[] objects) {
        super(context, textViewResourceId, objects);
        myContext = context;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        // return super.getView(position, convertView, parent);

        LayoutInflater inflater = (LayoutInflater) myContext
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View row = inflater.inflate(R.layout.row, parent, false);
        TextView label = (TextView) row.findViewById(R.id.month);
        label.setText(month[position]);
        ImageView icon = (ImageView) row.findViewById(R.id.icon);

        //Set icon here
        icon.setImageResource(R.drawable.ic_launcher);

        return row;
    }

}

String[] month = { " ", "Abstract", "Animal", "Anime", "Artistic", "Cartoon", "Comics",
        "Celeberity", "Cars", "Fantasy", "Food" };

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    /*
     * ListAdapter myListAdapter = new ArrayAdapter<String>( getActivity(),
     * android.R.layout.simple_list_item_1, month);
     * setListAdapter(myListAdapter);
     */
    MyListAdapter myListAdapter = new MyListAdapter(getActivity(),
            R.layout.row, month);
    setListAdapter(myListAdapter);
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {
    return inflater.inflate(R.layout.fragments_layout2, container, false);
}

@Override
public void onListItemClick(ListView l, View v, int position, long id) {
    Toast.makeText(getActivity(),
            getListView().getItemAtPosition(position).toString(),
            Toast.LENGTH_LONG).show();
}

}

Solution

  • Make an array of the Drawable ids just like you have made the month[] array in the Adapter.

    int[] drawables = {R.drawable.icon1, R.drawable.icon2, R.drawable.icon3, R.drawable.icon4};
    

    Then access the array just like you have used the month array to set the text of the TextView

    icon.setImageResource(drawables[position]);