Age Calculator – AutoComplete Field

A screenshot showing the AutoComplete field in action

I don’t want to use a calendar selector. You’re always hunting backwards and forwards for the correct month. I decided it would be better to use an AutoComplete text field. The most you ever have to do is click 3 letters, but that is only if you are born in June or July.

It is a bit fiddly, but very straight-forward. And I think it is very user friendly. Thanks to Sai Geetha’s Blog – Android – Auto Complete Text View | Android Beginner Dev Tutorial.

Screenshot showing the dropdown in action if you type the letter J

In the layout you need an AutoCompleteTextField as follows. Basically it is identical to EditText – just has a different tag.

    <AutoCompleteTextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/edit_month" 
    />

In the project, in the values folder, add a new resource file called months.xml. These are the values that it will use in the autocomplete.

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string-array name="months">
        <item >January</item>
        <item >February</item>
        <item >March</item>
        <item >April</item>
        <item >May</item>
        <item >June</item>
        <item >July</item>
        <item >August</item>
        <item >September</item>
        <item >October</item>
        <item >November</item>
        <item >December</item>
    </string-array>
</resources>

Then in ActivityMain you hook it all together.

  • Load the month names from your array in Resources
  • Put this array into a layout field adapter
    • You could make your own XML for the layout, but I’m happy with simple_list_item_1
  • Locate the the text field in the layout file
  • The threshold is how many letters you have to type before it will suggest anything
    • In a short list like this, 1 is perfect – for a long list 3 will probably be better
  • Add the adapter to the text field
        val monthNames =resources.getStringArray(R.array.months)
        val adapter: ArrayAdapter<String> =
            ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, monthNames)

        birthMonth = findViewById(R.id.edit_month) as AutoCompleteTextView
        birthMonth!!.setThreshold(1)
        birthMonth!!.setAdapter(adapter)

Leave a Reply

Your email address will not be published. Required fields are marked *