Friday, November 9, 2012

Styling an AutoCompleteTextView

I ran into some confusion recently styling some AutoCompleteTextViews.  An AutoCompleteTextView is a compound View - it's got both an EditText component and a floating dropdown component.  The former is rather straightforward to style, by the dropdown is difficult because it's a mixture of attributes on the AutoCompleteTextView itself and styles set in the theme via android:dropDownListViewStyle.

For example, if you want to setup a custom background on the dropdown, you do it in the AutoCompleteTextView:

<AutoCompleteTextView
  android:layout_width="match_parent"
  android:layout_height="wrap_content"
  android:popupBackground="@drawable/bg_autocomplete" />

But if you want to change the dividers, you have to create a theme and point that to a style, which isn't an immediately obvious solution:

<style name="MyTheme">
  <item name="android:dropDownListViewStyle">@style/DropDownListViewStyle</item>
</style>

<style name="DropDownListViewStyle">
  <item name="android:divider">#4F4F4F</item>
  <item name="android:dividerHeight">1dp</item>
</style>

The worst is when attributes in the AutoCompleteTextView and normal ListView styles collide.  I made the mistake of assuming that since it adopts a ListView-like style, it would adopt all ListView attributes - like android:listSelector.  The below, however, does not work:

<style name="DropDownListViewStyle">
  <item name="android:listSelector">@drawable/list_selector</item>
</style>

Instead, AutoCompleteTextView has its own attribute, android:dropDownSelector.  You have to set it like this:

<AutoCompleteTextView
  android:layout_width="match_parent"
  android:layout_height="wrap_content"
  android:dropDownSelector="@drawable/list_selector" />

1 comment: