Duplicate android:id in Layout
ID |
kotlin.android_duplicate_ids |
Severity |
low |
Remediation Complexity |
trivial |
Remediation Risk |
low |
Remediation Effort |
low |
Resource |
Reliability |
Language |
Kotlin |
Tags |
android, best-practice, reliability |
Description
Reports elements in the same Android layout XML file that declare the same android:id value. Duplicate IDs make findViewById return an arbitrary match and can crash fragment-transaction APIs.
Rationale
When two or more elements share the same android:id in a single layout, only one of them can be reliably found at runtime. Activity.findViewById() and View.findViewById() return whichever match the framework encounters first during tree traversal, making the result non-deterministic if the layout is restructured. Fragment transactions that reference the duplicated ID may target the wrong container, leading to crashes or misplaced fragments.
<!-- Bad: two elements share the same ID -->
<LinearLayout ...>
<TextView android:id="@+id/title" android:text="First" />
<TextView android:id="@+id/title" android:text="Second" />
</LinearLayout>
Remediation
Assign a unique android:id to each element within the same layout file.
<!-- Good: unique IDs -->
<LinearLayout ...>
<TextView android:id="@+id/title" android:text="First" />
<TextView android:id="@+id/subtitle" android:text="Second" />
</LinearLayout>