Eric Bergman-Terrell's Blog

Android Programming Tip: How to Embed EditText Views in a ListView (Don't!)
December 7, 2012

My new EBTCalc programmable calculator app can prompt the user for various values, from a custom button Javascript method:

var Prompt = com.ericbt.rpncalc.javascript.Prompt()
...

Dates.EnterDateTime = function() {
  var values = Prompt.prompt(
    [ 
      ["Year", "v", "[0-9]{4}", ""],
      ["Month", "s", "1|2|3|4|5|6|7|8|9|10|11|12", ""],
      ["Day", "v", "[0-9]{1,2}", ""],
      ["Time (hh:mm)", "v", "[0-9]{1,2}:[0-9]{1,2}", "00:00"],
      ["am/pm", "s", "AM|PM", "1"]
    ], "Enter Date/Time")

  if (values != null) {
    return new Date(values[1] + "/" + values[2] + "/" + values[0] + " " + values[3] + " " + values[4])
  }
}
EBTCalc Prompt Activity

My first implementation was an Activity with a ListView. Each ListView item contained a TextView label and an EditText and Spinner for the value entered by the user. This implementation seemed to work in the Android emulator, but did not properly work on an actual Android tablet. I was never able to get the focus to work properly with the EditText.

I'm sure it's possible to get an EditText to work properly inside of a ListView element, but I was not able to get it to work after trying various recommendations from StackOverflow.

My second implementation was to populate a TableLayout with the fields. The good news is that EditText focusing works properly with no additional effort. The bad news is that there isn't a built-in mechanism to bind a TableLayout to an Adapter. However, populating a TableLayout with code is not hard. Just create TableRows by inflating a TableRow layout, and add them with the addView method:

...
		TableLayout fieldsTableLayout = (TableLayout) findViewById(R.id.FieldsTableLayout);
		
		for (final PromptItem promptItem : Prompt.getPromptItems()) {
			TableRow tableRow = (TableRow) getLayoutInflater().inflate(R.layout.prompt_table_row, null);
			
			final TextView label = (TextView) tableRow.findViewById(R.id.Label);
			label.setText(String.format("%s:", promptItem.getLabelText()));

			final Spinner spinner = (Spinner) tableRow.findViewById(R.id.SpinnerField);
			
			final EditText editText = (EditText) tableRow.findViewById(R.id.TextField);

...
			fieldsTableLayout.addView(tableRow);
...

Keywords: Android, ListView, EditText, Focus, TableLayout, Data Binding, Adapter, Spinner

Reader Comments

Comment on this Blog Post

Recent Posts

TitleDate
EBTCalc (Android) Version 1.53 is now availableMay 19, 2024
Vault 3 Security EnhancementsOctober 24, 2023
Vault 3 is now available for Apple OSX M2 Mac Computers!September 18, 2023
Vault (for Desktop) Version 0.77 ReleasedMarch 26, 2023
EBTCalc (Android) Version 1.44 is now availableOctober 12, 2021
Vault (Desktop) Version 0.72 ReleasedOctober 6, 2021
EBT Compass is Now Available for Android DevicesJune 2, 2021