TableLayout

A TableLayout and a GridView arrange little views into rows and columns. Use a TableLayout when you care about which view is in which column. Use a GridView when you don’t care.

See Android’s TableLayout tutorial and example.

The TableLayout in main.xml contains three rows and a horizontal line above the last row. Column 1 (the column of EditTexts) is wide because of android:stretchColumns="1".

The attribute android:inputType="numberDecimal" allows only numeric input, not letters or newlines. It does not allow + or signs, but does allow a decimal point and fraction.

The attribute style="@android:style/Widget.EditText" gives the last TextView the same style as an EditText. By default, the TextView would have a smaller font size; see the first column. Widget.EditText is defined in android-sdks/platforms/android-14/data/res/values/styles.xml:

	<style name="Widget.EditText">
		<item name="android:focusable">true</item>
		<item name="android:focusableInTouchMode">true</item>
		<item name="android:clickable">true</item>
		<item name="android:background">?android:attr/editTextBackground</item>
		<item name="android:textAppearance">?android:attr/textAppearanceMediumInverse</item>
		<item name="android:textColor">?android:attr/editTextColor</item>
		<item name="android:gravity">center_vertical</item>
	</style>

Source code in TableLayout.zip

  1. TableLayoutActivity.java
  2. main.xml
  3. AndroidManifest.xml

Things to try

  1. Do not allow the user to type three or more digits to the right of the decimal point.

  2. Can we remove the bracket that underlines the total? on the screen

TableLayout in ApiDemos/Views/Layouts/TableLayout

  1. 01. Basic. Three rows and three columns.
    1. TableLayout1.java
    2. table_layout_1.xml
    3. strings.xml
  2. 02. Empty Cells. Three rows and two columns. Some rows are less than two columns. A non-trailing cell with android:visibility="invisible"
    1. TableLayout2.java
    2. table_layout_2.xml
    3. strings.xml
  3. 03. Long Content. Four columns. One row has more cells than the others. android:shrinkColumns="2, 3". Unicode \u2026 is horizontal ellipses (…).
    1. TableLayout3.java
    2. table_layout_3.xml
    3. strings.xml
  4. 04. Stretchable. android:stretchColumns="1" and android:gravity="right".
    1. TableLayout4.java
    2. table_layout_4.xml
    3. strings.xml
  5. 07. Column Collapse. The setColumnCollapsed method of class TableLayout. Add a row to a table dynamically.
    1. TableLayout7.java
    2. table_layout_7.xml
    3. strings.xml
  6. 12. Cell Spanning. android:layout_span="2". Like the HTML table COLSPAN attribute. For spanning rows, see nested LinearLayouts.
    1. TableLayout12.java
    2. table_layout_12.xml
    3. strings.xml