AdapterView Must Not Declare Inline Children
ID |
kotlin.android_adapter_children |
Severity |
low |
Remediation Complexity |
trivial |
Remediation Risk |
low |
Remediation Effort |
low |
Resource |
Reliability |
Language |
Kotlin |
Tags |
android, reliability |
Description
Reports AdapterView subclasses (ListView, GridView, Spinner, Gallery, ExpandableListView) that declare inline child elements in Android layout XML files. The Android framework silently ignores any children declared in XML for these views because their content is populated programmatically via an Adapter.
Rationale
AdapterView is designed to be populated at runtime by an Adapter that maps data to child views on demand. When developers add child elements directly inside a ListView or GridView in XML, those children are silently discarded. The UI appears empty, leading to confusion.
<!-- Bad: ListView with inline children (silently ignored) -->
<ListView
android:id="@+id/list"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="This text is never displayed" />
</ListView>
Remediation
Remove all inline children from the AdapterView element. Instead, define the item layout in a separate XML file and supply it through an Adapter in your Activity or Fragment code.
<!-- Good: empty AdapterView, populated by adapter -->
<ListView
android:id="@+id/list"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
// Populate the ListView programmatically
val list = findViewById<ListView>(R.id.list)
val adapter = ArrayAdapter(this, android.R.layout.simple_list_item_1, items)
list.adapter = adapter