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
Java Programming Tip: SWT Photo Frame ProgramOctober 31, 2016
Vault 3 (Desktop) Version 1.63 ReleasedSeptember 9, 2016
"Compliance with Court Orders Act of 2016"April 9, 2016
Disable "Visual Voicemail" on Android / T-MobileJanuary 17, 2016
IPv6 HumorDecember 10, 2015
Java Programming Tip: Specify the JVM time zoneDecember 7, 2015
Node.js / Express Programming Tip: Detect and Fix Memory LeaksOctober 27, 2015