Skip to content
Tutorials Center
My learning

Topics

Lesson 48 of 104 ยท Legacy Views

ListView, GridView, Spinner and Adapters (Legacy Views)

Learn the classic Android adapter widgets: ListView, ArrayAdapter, BaseAdapter with convertView, GridView, Spinner, custom spinners and ExpandableListView, plus when to move to RecyclerView.

Before RecyclerView there was AdapterView: a family of widgets (ListView, GridView, Spinner, ExpandableListView) that all follow the same idea. A widget shows rows, and an adapter supplies them. You will meet these classes in older code bases, in Material tutorials written before 2017 and in some framework screens such as the system Spinner drop-down. New screens should use RecyclerView or Compose lazy lists, but reading and migrating legacy code needs this vocabulary.

The Android classes cannot run on this site, so every Android snippet below is read-only. The TryIts are plain Kotlin stand-ins that model the adapter contract and the view-reuse trick, and each one says what is real and what is simplified.

The adapter contract

An adapter sits between your data and the widget. Whatever the widget type, the adapter answers the same questions:

Method Question the widget asks
getCount() How many rows are there?
getItem(position) Which data object belongs to row n?
getItemId(position) What stable ID does row n have?
getView(position, convertView, parent) Give me a view for row n.

You attach the adapter with setAdapter(adapter). Change the data, then call notifyDataSetChanged() and the widget asks again. The widget keeps only the rows on screen. When a row scrolls off, its view comes back as convertView for the next row, so you can reuse it instead of inflating a new one. That is the ancestor of the ViewHolder in RecyclerView.

flowchart LR
    D["Data list"] --> A["Adapter<br/>getCount, getView"]
    A --> W["ListView, GridView,<br/>Spinner, ExpandableListView"]
    W -->|"scrolls a row away"| A
    A -->|"convertView to reuse"| W

The widget asks for views; the adapter binds data to a recycled view or inflates a new one.

ListView with ArrayAdapter

ArrayAdapter is the quickest way to show a list of strings. It inflates a layout that contains a single TextView and calls toString() on each item.

Kotlin
// read-only example: the simplest ListView
val courses = listOf("Kotlin", "Compose", "Room", "Retrofit")

val adapter = ArrayAdapter(
    this,                                   // Context
    android.R.layout.simple_list_item_1,    // row layout with one TextView
    courses                                 // data
)
binding.courseList.adapter = adapter

binding.courseList.setOnItemClickListener { _, _, position, _ ->
    Toast.makeText(this, courses[position], Toast.LENGTH_SHORT).show()
}

The matching XML is a single element: <ListView android:id="@+id/courseList" android:layout_width="match_parent" android:layout_height="match_parent" />.

If each row needs more than one text (an icon, a title, a subtitle), the string-only ArrayAdapter is not enough. You have three choices:

  • Extend ArrayAdapter<T> and override getView, passing your own row layout and the ID of the TextView that should show text (the textViewResourceId parameter). Simple when only one view in the row changes.
  • Use SimpleAdapter, which maps keys of a list of maps to view IDs. Handy for quick prototypes, clumsy for anything typed.
  • Extend BaseAdapter and implement the four methods above. This is the most flexible and the one you will see most often.

A custom BaseAdapter

Kotlin
// read-only example: BaseAdapter with convertView reuse
class CourseAdapter(
    private val context: Context,
    private val courses: List<Course>
) : BaseAdapter() {

    override fun getCount() = courses.size
    override fun getItem(position: Int) = courses[position]
    override fun getItemId(position: Int) = courses[position].id.toLong()

    override fun getView(position: Int, convertView: View?, parent: ViewGroup): View {
        val binding = if (convertView == null) {
            ItemCourseBinding.inflate(LayoutInflater.from(context), parent, false)
                .also { it.root.tag = it }                       // remember the binding on the view
        } else {
            convertView.tag as ItemCourseBinding                 // reuse it
        }
        val course = getItem(position)
        binding.title.text = course.title
        binding.lessons.text = "${course.lessons} lessons"
        return binding.root
    }
}

Two rules apply, exactly as in RecyclerView:

  1. Reuse convertView when it is not null. Inflating a row from XML is the expensive step, and a fast fling would inflate hundreds of them.
  2. Always assign every field. The reused view still carries the old row's data, so a missing else branch makes checkboxes and images jump around while scrolling.

Storing the binding (or a hand-written holder) in view.tag avoids repeated findViewById calls, which is the "ViewHolder pattern" before RecyclerView made it mandatory.

Kotlin getView and convertView reuse (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

The stand-in does not draw anything, but the numbers are the point: seven rows are inflated once, then recycled 493 times.

GridView

GridView arranges items in a scrolling grid of rows and columns. You set the column count with android:numColumns (or "auto_fit" together with android:columnWidth), spacing with android:horizontalSpacing and android:verticalSpacing, and attach the same kind of adapter you use for a list.

XML
<!-- read-only example -->
<GridView
    android:id="@+id/courseGrid"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:numColumns="2"
    android:horizontalSpacing="8dp"
    android:verticalSpacing="8dp"
    android:stretchMode="columnWidth" />
Kotlin
// read-only example: GridView with a custom ArrayAdapter
class CourseGridAdapter(context: Context, courses: List<Course>) :
    ArrayAdapter<Course>(context, 0, courses) {

    override fun getView(position: Int, convertView: View?, parent: ViewGroup): View {
        val view = convertView
            ?: LayoutInflater.from(context).inflate(R.layout.item_course_card, parent, false)
        val course = getItem(position)!!
        view.findViewById<TextView>(R.id.title).text = course.title
        view.findViewById<ImageView>(R.id.icon).setImageResource(course.iconRes)
        return view
    }
}

GridView has two limits that push people to RecyclerView: every cell has the same size, and there are no item animations or DiffUtil. For a Pinterest-like grid with uneven heights you use RecyclerView with a StaggeredGridLayoutManager; for a fixed grid, GridLayoutManager. Compose uses LazyVerticalGrid and LazyVerticalStaggeredGrid (see Lazy lists and grids).

Spinner: the drop-down

A Spinner shows the selected item and opens a drop-down of the others. It is an AdapterView too, so the pattern is the same: set an adapter, listen for a selection.

XML
<!-- read-only example -->
<Spinner
    android:id="@+id/levelSpinner"
    android:layout_width="match_parent"
    android:layout_height="wrap_content" />
Kotlin
// read-only example: Spinner with a string-array resource
val adapter = ArrayAdapter.createFromResource(
    this, R.array.levels, android.R.layout.simple_spinner_item
).also {
    it.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item)
}
binding.levelSpinner.adapter = adapter

binding.levelSpinner.onItemSelectedListener = object : AdapterView.OnItemSelectedListener {
    override fun onItemSelected(parent: AdapterView<*>, view: View?, position: Int, id: Long) {
        val level = parent.getItemAtPosition(position) as String
        // react to the choice
    }
    override fun onNothingSelected(parent: AdapterView<*>) = Unit
}

The strings live in res/values/arrays.xml as a <string-array name="levels">, which also makes them translatable (Accessibility and localization). Two details trip people up:

  • A Spinner calls onItemSelected once at start-up with the initial selection, not only when the user taps. Ignore the first call or compare against the current state.
  • A spinner has two views per item: the closed view and the drop-down view. That is why setDropDownViewResource exists.

A custom spinner

If each entry needs an icon or two lines of text, extend ArrayAdapter and override both getView (closed state) and getDropDownView (open list), often delegating to one helper:

Kotlin
// read-only example: a spinner with a flag and a country name
class CountryAdapter(context: Context, private val countries: List<Country>) :
    ArrayAdapter<Country>(context, 0, countries) {

    override fun getView(position: Int, convertView: View?, parent: ViewGroup) =
        bind(position, convertView, parent)

    override fun getDropDownView(position: Int, convertView: View?, parent: ViewGroup) =
        bind(position, convertView, parent)

    private fun bind(position: Int, convertView: View?, parent: ViewGroup): View {
        val view = convertView
            ?: LayoutInflater.from(context).inflate(R.layout.item_country, parent, false)
        val country = countries[position]
        view.findViewById<ImageView>(R.id.flag).setImageResource(country.flagRes)
        view.findViewById<TextView>(R.id.name).text = country.name
        return view
    }
}

In a Material app you will usually prefer an ExposedDropdownMenu (XML) or ExposedDropdownMenuBox (Compose), which is the modern look of the same idea.

ExpandableListView and BaseExpandableListAdapter

ExpandableListView shows groups that expand to reveal children, such as chapters that unfold to lessons. Its adapter must provide two levels: group counts and child counts per group.

Kotlin
// read-only example: the methods BaseExpandableListAdapter asks for
class ChapterAdapter(
    private val context: Context,
    private val chapters: List<String>,
    private val lessons: Map<String, List<String>>
) : BaseExpandableListAdapter() {

    override fun getGroupCount() = chapters.size
    override fun getChildrenCount(group: Int) = lessons[chapters[group]]?.size ?: 0
    override fun getGroup(group: Int) = chapters[group]
    override fun getChild(group: Int, child: Int) = lessons.getValue(chapters[group])[child]
    override fun getGroupId(group: Int) = group.toLong()
    override fun getChildId(group: Int, child: Int) = child.toLong()
    override fun hasStableIds() = false
    override fun isChildSelectable(group: Int, child: Int) = true

    override fun getGroupView(group: Int, isExpanded: Boolean, convertView: View?, parent: ViewGroup): View {
        val view = convertView ?: LayoutInflater.from(context).inflate(R.layout.item_group, parent, false)
        view.findViewById<TextView>(R.id.title).text = getGroup(group)
        return view
    }

    override fun getChildView(group: Int, child: Int, isLast: Boolean, convertView: View?, parent: ViewGroup): View {
        val view = convertView ?: LayoutInflater.from(context).inflate(R.layout.item_child, parent, false)
        view.findViewById<TextView>(R.id.title).text = getChild(group, child)
        return view
    }
}

You attach it with expandableList.setAdapter(...) and react with setOnChildClickListener. In RecyclerView the same screen is one list with two view types, and in Compose a LazyColumn with stickyHeader or AnimatedVisibility.

The next stand-in models the two-level contract: it flattens groups and their children into the list of rows the widget would show, depending on which groups are expanded.

Kotlin Expandable groups flattened into rows (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

The real widget also remembers expansion across notifyDataSetChanged() only if hasStableIds() is true and your IDs are stable. This is another reason legacy code is fragile.

ListView, GridView and Spinner versus RecyclerView

Need AdapterView widgets RecyclerView
Row reuse optional (you must use convertView) enforced by ViewHolder
Layouts list, grid list, grid, staggered, custom
Item animations no yes (ItemAnimator)
Efficient updates notifyDataSetChanged() only DiffUtil, ListAdapter
Headers and footers addHeaderView() concatenated adapters, view types
Nested scrolling awkward works with NestedScrollView rules

A good migration plan: keep legacy screens that work, write new lists in Compose, and replace a ListView with a RecyclerView when you touch it for another reason. The stable-ID and getItemViewType ideas carry over directly.

Common mistakes

  • Putting a ListView inside a ScrollView. Both want to scroll, and the list collapses to one row. Use one scrolling container or a RecyclerView with nestedScrollingEnabled.
  • Ignoring convertView and inflating each time. Scrolling stutters.
  • Forgetting to reset optional parts of a row (a badge, a checkbox) in the reused view.
  • Calling notifyDataSetChanged() on a copy of the data. The adapter must hold the same list you modify, or you must hand it the new list.
  • Treating the first onItemSelected of a Spinner as a user action.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does the convertView parameter of getView contain?

    convertView is an old row view handed back by the widget so you can bind new data instead of inflating again. It is null only when nothing is available to reuse.
  2. 2. Which adapter class do you extend to give each row of a ListView several different views and full control?

    BaseAdapter lets you implement getCount, getItem, getItemId and getView yourself. ListAdapter belongs to RecyclerView.
  3. 3. Why does a Spinner need both getView and getDropDownView in a custom adapter?

    The closed state shows the selected item with getView; the open list is built with getDropDownView. Often both call the same helper.
  4. 4. What is a main reason to prefer RecyclerView over GridView?

    RecyclerView enforces view reuse, animates item changes and supports list, grid and staggered layouts.

Summary

  • ListView, GridView, Spinner and ExpandableListView are AdapterView widgets driven by an adapter.
  • Implement getCount, getItem, getItemId and getView; reuse convertView and assign every field.
  • ArrayAdapter suits string lists, BaseAdapter suits custom rows, BaseExpandableListAdapter adds a group level.
  • Spinners need a drop-down layout and fire an initial selection callback.
  • Prefer RecyclerView or Compose lazy lists for new work.

Next: Views and Compose side by side.