1

I'm using the following code for the dynamic ListView. I need to add some images in fromt of the text in the ListView

ListView listView = (ListView) menu.findViewById(R.id.list);
initListView(this, listView, "", 5, android.R.layout.simple_list_item_1);

public  void initListView(Context context, ListView listView, String prefix, int numItems, int layout) {
    // By using setAdpater method in listview we an add string array in list.
    String[] arr ={"A","B","C","D","E"};

    listView.setAdapter(new ArrayAdapter<String>(context, layout, arr));
    listView.setOnItemClickListener(new OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

        }
    });
}

Please let me know how to add images in my code.

1
  • 1
    you can't do that using ArrayAdapter. Create a CustomAdapter for it. Search for tutorial on here Commented Sep 28, 2012 at 7:49

4 Answers 4

2

you could use this kind of adapter :

public class CustomAdapter extends BaseAdapter{

String[] arr ={"A","B","C","D","E"};
Context context;

public CustomAdapter(Context context){
    this.context = context;
}

@Override
public int getCount() {
    return arr.length;
}

@Override
public String getItem(int arg0) {
    return arr[arg0];
}

@Override
public long getItemId(int arg0) {
    return 0;
}

@Override
public View getView(int arg0, View arg1, ViewGroup arg2) {
    LinearLayout layout = new LinearLayout(context);
    layout.setOrientation(LinearLayout.HORIZONTAL);

    TextView text = new TextView(context);
    text.setText(getItem(arg0));

    ImageView image = new ImageView(context);
    image.setImageResource(android.R.drawable.ic_menu_gallery);
    layout.addView(image);
    layout.addView(text);

    return layout;
}

}
Sign up to request clarification or add additional context in comments.

Comments

1

By using custom adapter you can add images to the listview items look at this tutorial it will help you
1. ListView in Android using custom ListAdapter

2.Android Custom ListView with Image and Text

Comments

1

As was already suggested, you need to use other Adapters like SimpleCursorAdapter

List with images can be quite complex if you want to load images from url also

I highly recomend you look at this code which has full implementation of ListView with Images with LazyLoading

https://github.com/thest1/LazyList

Comments

1

This is a modified version of the LazyList project with quite some additions: https://github.com/nostra13/Android-Universal-Image-Loader I'm using it in some projects and its quite good!

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.