ArrayAdapter in android to create simple listview

Nirav Kamani picture Nirav Kamani · Sep 29, 2013 · Viewed 228.1k times · Source

I tried to create an Activity in Android, This Activity only contains a ListView nothing else.

As I know to fill the listview we need to use an ArrayAdapter.

So to understand the ArrayAdapter I have read the following link:

http://developer.android.com/reference/android/widget/ArrayAdapter.html

But still I am unable to understand it clearly!

One of the biggest doubt is why the constructor needs a TextView resource id while my activity is not having any TextViews what I should have to give it?

I am not saying that this is the only constructor, just that I'm unable to understand the logic behind it.

In order to create a simple listview I also referred to the following link:

Simple ListView using ArrayAdapter example.

But again my main doubt is why it does it need a TextView resource id?

If anybody can explain it with an example it will be very helpful.

EDIT:

ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
          android.R.layout.simple_list_item_1, android.R.id.text1, values);

Answer

ucsunil picture ucsunil · Jan 14, 2014

ArrayAdapter uses a TextView to display each item within it. Behind the scenes, it uses the toString() method of each object that it holds and displays this within the TextView. ArrayAdapter has a number of constructors that can be used and the one that you have used in your example is:

ArrayAdapter(Context context, int resource, int textViewResourceId, T[] objects)

By default, ArrayAdapter uses the default TextView to display each item. But if you want, you could create your own TextView and implement any complex design you'd like by extending the TextView class. This would then have to go into the layout for your use. You could reference this in the textViewResourceId field to bind the objects to this view instead of the default.

For your use, I would suggest that you use the constructor:

ArrayAdapter(Context context, int resource, T[] objects). 

In your case, this would be:

ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, values)

and it should be fine. This will bind each string to the default TextView display - plain and simple white background.

So to answer your question, you do not have to use the textViewResourceId.