Fix for http://b/issue?id=5081478

GridLayout needs to call measure on children after it knows how large children should be

Also:

. Remove deprecated methods and XML attributes.
. Stop Spaces having margins by default.
. Remove getSpacers() and findUsed()
. Change default for row/columnOrderPreserved() from false to true.
. Improve automatic index allocation mechanism to use individual maxima.

Change-Id: Id79fbb2e70a0bf2002191ec2a9746547d896de72
diff --git a/api/current.txt b/api/current.txt
index c6775bf..11e38a5 100644
--- a/api/current.txt
+++ b/api/current.txt
@@ -184,19 +184,19 @@
   public static final class R.attr {
     ctor public R.attr();
     field public static final int absListViewStyle = 16842858; // 0x101006a
-    field public static final int accessibilityEventTypes = 16843646; // 0x101037e
-    field public static final int accessibilityFeedbackType = 16843648; // 0x1010380
-    field public static final int accessibilityFlags = 16843650; // 0x1010382
+    field public static final int accessibilityEventTypes = 16843644; // 0x101037c
+    field public static final int accessibilityFeedbackType = 16843646; // 0x101037e
+    field public static final int accessibilityFlags = 16843648; // 0x1010380
     field public static final int accountPreferences = 16843423; // 0x101029f
     field public static final int accountType = 16843407; // 0x101028f
     field public static final int action = 16842797; // 0x101002d
     field public static final int actionBarSize = 16843499; // 0x10102eb
-    field public static final int actionBarSplitStyle = 16843668; // 0x1010394
+    field public static final int actionBarSplitStyle = 16843666; // 0x1010392
     field public static final int actionBarStyle = 16843470; // 0x10102ce
     field public static final int actionBarTabBarStyle = 16843508; // 0x10102f4
     field public static final int actionBarTabStyle = 16843507; // 0x10102f3
     field public static final int actionBarTabTextStyle = 16843509; // 0x10102f5
-    field public static final int actionBarWidgetTheme = 16843683; // 0x10103a3
+    field public static final int actionBarWidgetTheme = 16843681; // 0x10103a1
     field public static final int actionButtonStyle = 16843480; // 0x10102d8
     field public static final int actionDropDownStyle = 16843479; // 0x10102d7
     field public static final int actionLayout = 16843515; // 0x10102fb
@@ -208,10 +208,10 @@
     field public static final int actionModeCopyDrawable = 16843538; // 0x1010312
     field public static final int actionModeCutDrawable = 16843537; // 0x1010311
     field public static final int actionModePasteDrawable = 16843539; // 0x1010313
-    field public static final int actionModeSelectAllDrawable = 16843644; // 0x101037c
-    field public static final int actionModeStyle = 16843680; // 0x10103a0
+    field public static final int actionModeSelectAllDrawable = 16843642; // 0x101037a
+    field public static final int actionModeStyle = 16843678; // 0x101039e
     field public static final int actionOverflowButtonStyle = 16843510; // 0x10102f6
-    field public static final int actionProviderClass = 16843669; // 0x1010395
+    field public static final int actionProviderClass = 16843667; // 0x1010393
     field public static final int actionViewClass = 16843516; // 0x10102fc
     field public static final int activatedBackgroundIndicator = 16843517; // 0x10102fd
     field public static final int activityCloseEnterAnimation = 16842938; // 0x10100ba
@@ -257,8 +257,8 @@
     field public static final int background = 16842964; // 0x10100d4
     field public static final int backgroundDimAmount = 16842802; // 0x1010032
     field public static final int backgroundDimEnabled = 16843295; // 0x101021f
-    field public static final int backgroundSplit = 16843671; // 0x1010397
-    field public static final int backgroundStacked = 16843670; // 0x1010396
+    field public static final int backgroundSplit = 16843669; // 0x1010395
+    field public static final int backgroundStacked = 16843668; // 0x1010394
     field public static final int backupAgent = 16843391; // 0x101027f
     field public static final int baseline = 16843548; // 0x101031c
     field public static final int baselineAlignBottom = 16843042; // 0x1010122
@@ -267,7 +267,7 @@
     field public static final int borderlessButtonStyle = 16843563; // 0x101032b
     field public static final int bottom = 16843184; // 0x10101b0
     field public static final int bottomBright = 16842957; // 0x10100cd
-    field public static final int bottomChevronDrawable = 16843657; // 0x1010389
+    field public static final int bottomChevronDrawable = 16843655; // 0x1010387
     field public static final int bottomDark = 16842953; // 0x10100c9
     field public static final int bottomLeftRadius = 16843179; // 0x10101ab
     field public static final int bottomMedium = 16842958; // 0x10100ce
@@ -286,7 +286,7 @@
     field public static final int cacheColorHint = 16843009; // 0x1010101
     field public static final int calendarViewShown = 16843596; // 0x101034c
     field public static final int calendarViewStyle = 16843613; // 0x101035d
-    field public static final int canRetrieveWindowContent = 16843651; // 0x1010383
+    field public static final int canRetrieveWindowContent = 16843649; // 0x1010381
     field public static final int candidatesTextStyleSpans = 16843312; // 0x1010230
     field public static final deprecated int capitalize = 16843113; // 0x1010169
     field public static final int centerBright = 16842956; // 0x10100cc
@@ -315,15 +315,15 @@
     field public static final int codes = 16843330; // 0x1010242
     field public static final int collapseColumns = 16843083; // 0x101014b
     field public static final int color = 16843173; // 0x10101a5
-    field public static final int colorActivatedHighlight = 16843676; // 0x101039c
+    field public static final int colorActivatedHighlight = 16843674; // 0x101039a
     field public static final int colorBackground = 16842801; // 0x1010031
     field public static final int colorBackgroundCacheHint = 16843435; // 0x10102ab
-    field public static final int colorFocusedHighlight = 16843675; // 0x101039b
+    field public static final int colorFocusedHighlight = 16843673; // 0x1010399
     field public static final int colorForeground = 16842800; // 0x1010030
     field public static final int colorForegroundInverse = 16843270; // 0x1010206
-    field public static final int colorLongPressedHighlight = 16843674; // 0x101039a
-    field public static final int colorMultiSelectHighlight = 16843677; // 0x101039d
-    field public static final int colorPressedHighlight = 16843673; // 0x1010399
+    field public static final int colorLongPressedHighlight = 16843672; // 0x1010398
+    field public static final int colorMultiSelectHighlight = 16843675; // 0x101039b
+    field public static final int colorPressedHighlight = 16843671; // 0x1010397
     field public static final int columnCount = 16843635; // 0x1010373
     field public static final int columnDelay = 16843215; // 0x10101cf
     field public static final int columnOrderPreserved = 16843636; // 0x1010374
@@ -380,11 +380,11 @@
     field public static final int drawSelectorOnTop = 16843004; // 0x10100fc
     field public static final int drawable = 16843161; // 0x1010199
     field public static final int drawableBottom = 16843118; // 0x101016e
-    field public static final int drawableEnd = 16843679; // 0x101039f
+    field public static final int drawableEnd = 16843677; // 0x101039d
     field public static final int drawableLeft = 16843119; // 0x101016f
     field public static final int drawablePadding = 16843121; // 0x1010171
     field public static final int drawableRight = 16843120; // 0x1010170
-    field public static final int drawableStart = 16843678; // 0x101039e
+    field public static final int drawableStart = 16843676; // 0x101039c
     field public static final int drawableTop = 16843117; // 0x101016d
     field public static final int drawingCacheQuality = 16842984; // 0x10100e8
     field public static final int dropDownAnchor = 16843363; // 0x1010263
@@ -441,7 +441,7 @@
     field public static final int fastScrollTextColor = 16843609; // 0x1010359
     field public static final int fastScrollThumbDrawable = 16843574; // 0x1010336
     field public static final int fastScrollTrackDrawable = 16843577; // 0x1010339
-    field public static final int feedbackCount = 16843663; // 0x101038f
+    field public static final int feedbackCount = 16843661; // 0x101038d
     field public static final int fillAfter = 16843197; // 0x10101bd
     field public static final int fillBefore = 16843196; // 0x10101bc
     field public static final int fillEnabled = 16843343; // 0x101024f
@@ -494,7 +494,7 @@
     field public static final int hand_hour = 16843011; // 0x1010103
     field public static final int hand_minute = 16843012; // 0x1010104
     field public static final int handle = 16843354; // 0x101025a
-    field public static final int handleDrawable = 16843653; // 0x1010385
+    field public static final int handleDrawable = 16843651; // 0x1010383
     field public static final int handleProfiling = 16842786; // 0x1010022
     field public static final int hapticFeedbackEnabled = 16843358; // 0x101025e
     field public static final int hardwareAccelerated = 16843475; // 0x10102d3
@@ -503,12 +503,12 @@
     field public static final int headerDividersEnabled = 16843310; // 0x101022e
     field public static final int height = 16843093; // 0x1010155
     field public static final int hint = 16843088; // 0x1010150
-    field public static final int hitRadius = 16843660; // 0x101038c
+    field public static final int hitRadius = 16843658; // 0x101038a
     field public static final int homeAsUpIndicator = 16843531; // 0x101030b
     field public static final int homeLayout = 16843549; // 0x101031d
     field public static final int horizontalDivider = 16843053; // 0x101012d
     field public static final int horizontalGap = 16843327; // 0x101023f
-    field public static final int horizontalOffset = 16843665; // 0x1010391
+    field public static final int horizontalOffset = 16843663; // 0x101038f
     field public static final int horizontalScrollViewStyle = 16843603; // 0x1010353
     field public static final int horizontalSpacing = 16843028; // 0x1010114
     field public static final int host = 16842792; // 0x1010028
@@ -554,7 +554,7 @@
     field public static final int installLocation = 16843447; // 0x10102b7
     field public static final int interpolator = 16843073; // 0x1010141
     field public static final int isAlwaysSyncable = 16843571; // 0x1010333
-    field public static final int isAuxiliary = 16843645; // 0x101037d
+    field public static final int isAuxiliary = 16843643; // 0x101037b
     field public static final int isDefault = 16843297; // 0x1010221
     field public static final int isIndicator = 16843079; // 0x1010147
     field public static final int isModifier = 16843334; // 0x1010246
@@ -607,8 +607,7 @@
     field public static final int layout_centerInParent = 16843151; // 0x101018f
     field public static final int layout_centerVertical = 16843153; // 0x1010191
     field public static final int layout_column = 16843084; // 0x101014c
-    field public static final deprecated int layout_columnFlexibility = 16843643; // 0x101037b
-    field public static final int layout_columnSpan = 16843642; // 0x101037a
+    field public static final int layout_columnSpan = 16843641; // 0x1010379
     field public static final int layout_gravity = 16842931; // 0x10100b3
     field public static final int layout_height = 16842997; // 0x10100f5
     field public static final int layout_margin = 16842998; // 0x10100f6
@@ -617,7 +616,6 @@
     field public static final int layout_marginRight = 16843001; // 0x10100f9
     field public static final int layout_marginTop = 16843000; // 0x10100f8
     field public static final int layout_row = 16843639; // 0x1010377
-    field public static final deprecated int layout_rowFlexibility = 16843641; // 0x1010379
     field public static final int layout_rowSpan = 16843640; // 0x1010378
     field public static final int layout_scale = 16843155; // 0x1010193
     field public static final int layout_span = 16843085; // 0x101014d
@@ -628,7 +626,7 @@
     field public static final int layout_x = 16843135; // 0x101017f
     field public static final int layout_y = 16843136; // 0x1010180
     field public static final int left = 16843181; // 0x10101ad
-    field public static final int leftChevronDrawable = 16843654; // 0x1010386
+    field public static final int leftChevronDrawable = 16843652; // 0x1010384
     field public static final int lineSpacingExtra = 16843287; // 0x1010217
     field public static final int lineSpacingMultiplier = 16843288; // 0x1010218
     field public static final int lines = 16843092; // 0x1010154
@@ -640,8 +638,8 @@
     field public static final int listDividerAlertDialog = 16843525; // 0x1010305
     field public static final int listPopupWindowStyle = 16843519; // 0x10102ff
     field public static final int listPreferredItemHeight = 16842829; // 0x101004d
-    field public static final int listPreferredItemHeightLarge = 16843666; // 0x1010392
-    field public static final int listPreferredItemHeightSmall = 16843667; // 0x1010393
+    field public static final int listPreferredItemHeightLarge = 16843664; // 0x1010390
+    field public static final int listPreferredItemHeightSmall = 16843665; // 0x1010391
     field public static final int listSelector = 16843003; // 0x10100fb
     field public static final int listSeparatorTextViewStyle = 16843272; // 0x1010208
     field public static final int listViewStyle = 16842868; // 0x1010074
@@ -672,8 +670,8 @@
     field public static final int minHeight = 16843072; // 0x1010140
     field public static final int minLevel = 16843185; // 0x10101b1
     field public static final int minLines = 16843094; // 0x1010156
-    field public static final int minResizeHeight = 16843682; // 0x10103a2
-    field public static final int minResizeWidth = 16843681; // 0x10103a1
+    field public static final int minResizeHeight = 16843680; // 0x10103a0
+    field public static final int minResizeWidth = 16843679; // 0x101039f
     field public static final int minSdkVersion = 16843276; // 0x101020c
     field public static final int minWidth = 16843071; // 0x101013f
     field public static final int mode = 16843134; // 0x101017e
@@ -689,7 +687,7 @@
     field public static final int nextFocusUp = 16842979; // 0x10100e3
     field public static final int noHistory = 16843309; // 0x101022d
     field public static final int normalScreens = 16843397; // 0x1010285
-    field public static final int notificationTimeout = 16843649; // 0x1010381
+    field public static final int notificationTimeout = 16843647; // 0x101037f
     field public static final int numColumns = 16843032; // 0x1010118
     field public static final int numStars = 16843076; // 0x1010144
     field public static final deprecated int numeric = 16843109; // 0x1010165
@@ -703,11 +701,11 @@
     field public static final int orderingFromXml = 16843239; // 0x10101e7
     field public static final int orientation = 16842948; // 0x10100c4
     field public static final int outAnimation = 16843128; // 0x1010178
-    field public static final int outerRadius = 16843659; // 0x101038b
+    field public static final int outerRadius = 16843657; // 0x1010389
     field public static final int overScrollFooter = 16843459; // 0x10102c3
     field public static final int overScrollHeader = 16843458; // 0x10102c2
     field public static final int overScrollMode = 16843457; // 0x10102c1
-    field public static final int packageNames = 16843647; // 0x101037f
+    field public static final int packageNames = 16843645; // 0x101037d
     field public static final int padding = 16842965; // 0x10100d5
     field public static final int paddingBottom = 16842969; // 0x10100d9
     field public static final int paddingLeft = 16842966; // 0x10100d6
@@ -792,7 +790,7 @@
     field public static final int restoreAnyVersion = 16843450; // 0x10102ba
     field public static final deprecated int restoreNeedsApplication = 16843421; // 0x101029d
     field public static final int right = 16843183; // 0x10101af
-    field public static final int rightChevronDrawable = 16843655; // 0x1010387
+    field public static final int rightChevronDrawable = 16843653; // 0x1010385
     field public static final int ringtonePreferenceStyle = 16842899; // 0x1010093
     field public static final int ringtoneType = 16843257; // 0x10101f9
     field public static final int rotation = 16843558; // 0x1010326
@@ -868,7 +866,7 @@
     field public static final int smallIcon = 16843422; // 0x101029e
     field public static final int smallScreens = 16843396; // 0x1010284
     field public static final int smoothScrollbar = 16843313; // 0x1010231
-    field public static final int snapMargin = 16843662; // 0x101038e
+    field public static final int snapMargin = 16843660; // 0x101038c
     field public static final int soundEffectsEnabled = 16843285; // 0x1010215
     field public static final int spacing = 16843027; // 0x1010113
     field public static final int spinnerDropDownItemStyle = 16842887; // 0x1010087
@@ -933,7 +931,7 @@
     field public static final int tag = 16842961; // 0x10100d1
     field public static final int targetActivity = 16843266; // 0x1010202
     field public static final int targetClass = 16842799; // 0x101002f
-    field public static final int targetDrawables = 16843652; // 0x1010384
+    field public static final int targetDrawables = 16843650; // 0x1010382
     field public static final int targetPackage = 16842785; // 0x1010021
     field public static final int targetSdkVersion = 16843376; // 0x1010270
     field public static final int taskAffinity = 16842770; // 0x1010012
@@ -948,7 +946,7 @@
     field public static final int tension = 16843370; // 0x101026a
     field public static final int testOnly = 16843378; // 0x1010272
     field public static final int text = 16843087; // 0x101014f
-    field public static final int textAllCaps = 16843672; // 0x1010398
+    field public static final int textAllCaps = 16843670; // 0x1010396
     field public static final int textAppearance = 16842804; // 0x1010034
     field public static final int textAppearanceButton = 16843271; // 0x1010207
     field public static final int textAppearanceInverse = 16842805; // 0x1010035
@@ -1022,7 +1020,7 @@
     field public static final int toYScale = 16843205; // 0x10101c5
     field public static final int top = 16843182; // 0x10101ae
     field public static final int topBright = 16842955; // 0x10100cb
-    field public static final int topChevronDrawable = 16843656; // 0x1010388
+    field public static final int topChevronDrawable = 16843654; // 0x1010386
     field public static final int topDark = 16842951; // 0x10100c7
     field public static final int topLeftRadius = 16843177; // 0x10101a9
     field public static final int topOffset = 16843352; // 0x1010258
@@ -1052,10 +1050,10 @@
     field public static final int verticalCorrection = 16843322; // 0x101023a
     field public static final int verticalDivider = 16843054; // 0x101012e
     field public static final int verticalGap = 16843328; // 0x1010240
-    field public static final int verticalOffset = 16843664; // 0x1010390
+    field public static final int verticalOffset = 16843662; // 0x101038e
     field public static final int verticalScrollbarPosition = 16843572; // 0x1010334
     field public static final int verticalSpacing = 16843029; // 0x1010115
-    field public static final int vibrationDuration = 16843661; // 0x101038d
+    field public static final int vibrationDuration = 16843659; // 0x101038b
     field public static final int visibility = 16842972; // 0x10100dc
     field public static final int visible = 16843156; // 0x1010194
     field public static final int vmSafeMode = 16843448; // 0x10102b8
@@ -1072,7 +1070,7 @@
     field public static final int wallpaperIntraOpenExitAnimation = 16843416; // 0x1010298
     field public static final int wallpaperOpenEnterAnimation = 16843411; // 0x1010293
     field public static final int wallpaperOpenExitAnimation = 16843412; // 0x1010294
-    field public static final int waveDrawable = 16843658; // 0x101038a
+    field public static final int waveDrawable = 16843656; // 0x1010388
     field public static final int webTextViewStyle = 16843449; // 0x10102b9
     field public static final int webViewStyle = 16842885; // 0x1010085
     field public static final int weekDayTextAppearance = 16843592; // 0x1010348
diff --git a/core/java/android/widget/GridLayout.java b/core/java/android/widget/GridLayout.java
index f999960..f354c6e 100644
--- a/core/java/android/widget/GridLayout.java
+++ b/core/java/android/widget/GridLayout.java
@@ -32,12 +32,13 @@
 import java.lang.reflect.Array;
 import java.util.ArrayList;
 import java.util.Arrays;
-import java.util.Collection;
 import java.util.HashMap;
 import java.util.List;
 import java.util.Map;
 
 import static android.view.Gravity.*;
+import static android.view.View.MeasureSpec.EXACTLY;
+import static android.view.View.MeasureSpec.makeMeasureSpec;
 import static java.lang.Math.max;
 import static java.lang.Math.min;
 
@@ -92,8 +93,21 @@
  *
  * <h4>Excess Space Distribution</h4>
  *
- * A child's ability to stretch is controlled using the flexibility
- * properties of its row and column groups.
+ * A child's ability to stretch is inferred from the alignment properties of
+ * its row and column groups (which are typically set by setting the
+ * {@link LayoutParams#setGravity(int) gravity} property of the child's layout parameters).
+ * If alignment was defined along a given axis then the component
+ * is taken as flexible in along that axis. If no alignment was set,
+ * the component is instead assumed to be inflexible. Multiple components in
+ * the same row or column group are considered to act in <em>parallel</em>. Such a
+ * group is flexible only if <em>all</em> of the components
+ * within it are flexible. Row and column groups that sit either side of a common boundary
+ * are instead considered to act in <em>series</em>. The composite group made of these two
+ * elements is flexible if <em>one</em> of its elements is flexible.
+ * <p>
+ * To make a column stretch, make sure all of the components inside it define a
+ * gravity. To prevent a column from stretching, ensure that one of the components
+ * in the column does not define a gravity.
  * <p>
  * <p>
  * See {@link GridLayout.LayoutParams} for a full description of the
@@ -175,7 +189,7 @@
     private static final int DEFAULT_ORIENTATION = HORIZONTAL;
     private static final int DEFAULT_COUNT = UNDEFINED;
     private static final boolean DEFAULT_USE_DEFAULT_MARGINS = false;
-    private static final boolean DEFAULT_ORDER_PRESERVED = false;
+    private static final boolean DEFAULT_ORDER_PRESERVED = true;
     private static final int DEFAULT_ALIGNMENT_MODE = ALIGN_MARGINS;
     private static final int DEFAULT_CONTAINER_MARGIN = 0;
     private static final int MAX_SIZE = 100000;
@@ -198,8 +212,6 @@
     private int mOrientation = DEFAULT_ORIENTATION;
     private boolean mUseDefaultMargins = DEFAULT_USE_DEFAULT_MARGINS;
     private int mAlignmentMode = DEFAULT_ALIGNMENT_MODE;
-    private Alignment mColumnAlignment = LEFT;
-    private Alignment mRowAlignment = BASELINE;
     private int mDefaultGap;
 
     // Constructors
@@ -440,22 +452,13 @@
     }
 
     /**
-     * When this property is {@code false}, the default state, GridLayout
-     * is at liberty to choose an order that better suits the heights of its children.
-     <p>
      * When this property is {@code true}, GridLayout is forced to place the row boundaries
      * so that their associated grid indices are in ascending order in the view.
      * <p>
-     * GridLayout implements this specification by creating ordering constraints between
-     * the variables that represent the locations of the row boundaries.
-     *
-     * When this property is {@code true}, constraints are added for each pair of consecutive
-     * indices: i.e. between row boundaries: {@code [0..1], [1..2], [2..3],...} etc.
-     *
-     * When the property is {@code false}, the ordering constraints are placed
-     * only between boundaries that separate opposing edges of the layout's children.
+     * When this property is {@code false} GridLayout is at liberty to place the vertical row
+     * boundaries in whatever order best fits the given constraints.
      * <p>
-     * The default value of this property is {@code false}.
+     * The default value of this property is {@code true}.
 
      * @param rowOrderPreserved {@code true} to force GridLayout to respect the order
      *        of row boundaries
@@ -485,22 +488,13 @@
     }
 
     /**
-     * When this property is {@code false}, the default state, GridLayout
-     * is at liberty to choose an order that better suits the widths of its children.
-     <p>
      * When this property is {@code true}, GridLayout is forced to place the column boundaries
      * so that their associated grid indices are in ascending order in the view.
      * <p>
-     * GridLayout implements this specification by creating ordering constraints between
-     * the variables that represent the locations of the column boundaries.
-     *
-     * When this property is {@code true}, constraints are added for each pair of consecutive
-     * indices: i.e. between column boundaries: {@code [0..1], [1..2], [2..3],...} etc.
-     *
-     * When the property is {@code false}, the ordering constraints are placed
-     * only between boundaries that separate opposing edges of the layout's children.
+     * When this property is {@code false} GridLayout is at liberty to place the horizontal column
+     * boundaries in whatever order best fits the given constraints.
      * <p>
-     * The default value of this property is {@code false}.
+     * The default value of this property is {@code true}.
      *
      * @param columnOrderPreserved use {@code true} to force GridLayout to respect the order
      *        of column boundaries.
@@ -533,6 +527,7 @@
         return result;
     }
 
+    @SuppressWarnings("unchecked")
     private static <T> T[] append(T[] a, T[] b) {
         T[] result = (T[]) Array.newInstance(a.getClass().getComponentType(), a.length + b.length);
         System.arraycopy(a, 0, result, 0, a.length);
@@ -559,6 +554,9 @@
     }
 
     private int getDefaultMargin(View c, boolean horizontal, boolean leading) {
+        if (c.getClass() == Space.class) {
+            return 0;
+        }
         return mDefaultGap / 2;
     }
 
@@ -594,72 +592,92 @@
         return (value != UNDEFINED) ? value : defaultValue;
     }
 
+    private static boolean fits(int[] a, int value, int start, int end) {
+        if (end > a.length) {
+            return false;
+        }
+        for (int i = start; i < end; i++) {
+            if (a[i] > value) {
+                return false;
+            }
+        }
+        return true;
+    }
+
+    private static void procrusteanFill(int[] a, int start, int end, int value) {
+        int length = a.length;
+        Arrays.fill(a, Math.min(start, length), Math.min(end, length), value);
+    }
+
+    private static void setCellGroup(LayoutParams lp, int row, int rowSpan, int col, int colSpan) {
+        lp.setRowSpecSpan(new Interval(row, row + rowSpan));
+        lp.setColumnSpecSpan(new Interval(col, col + colSpan));
+    }
+
+    // Logic to avert infinite loops by ensuring that the cells can be placed somewhere.
+    private static int clip(Interval minorRange, boolean minorWasDefined, int count) {
+        int size = minorRange.size();
+        if (count == 0) {
+            return size;
+        }
+        int min = minorWasDefined ? min(minorRange.min, count) : 0;
+        return min(size, count - min);
+    }
+
     // install default indices for cells that don't define them
     private void validateLayoutParams() {
-        new Object() {
-            public int maxSize = 0;
+        final boolean horizontal = (mOrientation == HORIZONTAL);
+        final int axisCount = horizontal ? mHorizontalAxis.count : mVerticalAxis.count;
+        final int count = valueIfDefined(axisCount, 0);
 
-            private int valueIfDefined2(int value, int defaultValue) {
-                if (value != UNDEFINED) {
-                    maxSize = 0;
-                    return value;
-                } else {
-                    return defaultValue;
-                }
+        int major = 0;
+        int minor = 0;
+        int[] maxSizes = new int[count];
+
+        for (int i = 0, N = getChildCount(); i < N; i++) {
+            LayoutParams lp = getLayoutParams1(getChildAt(i));
+
+            final Interval majorRange = (horizontal ? lp.rowSpec : lp.columnSpec).span;
+            final boolean majorWasDefined = (majorRange.min != UNDEFINED);
+            final int majorSpan = majorRange.size();
+            if (majorWasDefined) {
+                major = majorRange.min;
             }
 
-            {
-                final boolean horizontal = (mOrientation == HORIZONTAL);
-                final int axis = horizontal ? mHorizontalAxis.count : mVerticalAxis.count;
-                final int count = valueIfDefined(axis, Integer.MAX_VALUE);
+            final Interval minorRange = (horizontal ? lp.columnSpec : lp.rowSpec).span;
+            final boolean minorWasDefined = (minorRange.min != UNDEFINED);
+            final int minorSpan = clip(minorRange, minorWasDefined, count);
+            if (minorWasDefined) {
+                minor = minorRange.min;
+            }
 
-                int row = 0;
-                int col = 0;
-                for (int i = 0, N = getChildCount(); i < N; i++) {
-                    View c = getChildAt(i);
-                    LayoutParams lp = getLayoutParams1(c);
-
-                    final Spec colSpec = lp.columnSpec;
-                    final Interval cols = colSpec.span;
-                    final int colSpan = cols.size();
-
-                    final Spec rowSpec = lp.rowSpec;
-                    final Interval rows = rowSpec.span;
-                    final int rowSpan = rows.size();
-
-                    if (horizontal) {
-                        row = valueIfDefined2(rows.min, row);
-
-                        int newCol = valueIfDefined(cols.min, (col + colSpan > count) ? 0 : col);
-                        if (newCol < col) {
-                            row += maxSize;
-                            maxSize = 0;
+            if (count != 0) {
+                // Find suitable row/col values when at least one is undefined.
+                if (!majorWasDefined || !minorWasDefined) {
+                    while (!fits(maxSizes, major, minor, minor + minorSpan)) {
+                        if (minorWasDefined) {
+                            major++;
+                        } else {
+                            if (minor + minorSpan <= count) {
+                                minor++;
+                            } else {
+                                minor = 0;
+                                major++;
+                            }
                         }
-                        col = newCol;
-                        maxSize = max(maxSize, rowSpan);
-                    } else {
-                        col = valueIfDefined2(cols.min, col);
-
-                        int newRow = valueIfDefined(rows.min, (row + rowSpan > count) ? 0 : row);
-                        if (newRow < row) {
-                            col += maxSize;
-                            maxSize = 0;
-                        }
-                        row = newRow;
-                        maxSize = max(maxSize, colSpan);
-                    }
-
-                    lp.setColumnSpecSpan(new Interval(col, col + colSpan));
-                    lp.setRowSpecSpan(new Interval(row, row + rowSpan));
-
-                    if (horizontal) {
-                        col = col + colSpan;
-                    } else {
-                        row = row + rowSpan;
                     }
                 }
+                procrusteanFill(maxSizes, minor, minor + minorSpan, major + majorSpan);
             }
-        };
+
+            if (horizontal) {
+                setCellGroup(lp, major, majorSpan, minor, minorSpan);
+            } else {
+                setCellGroup(lp, minor, minorSpan, major, majorSpan);
+            }
+
+            minor = minor + minorSpan;
+        }
         invalidateStructure();
     }
 
@@ -667,7 +685,7 @@
         mLayoutParamsValid = false;
         mHorizontalAxis.invalidateStructure();
         mVerticalAxis.invalidateStructure();
-        // This can end up being done twice. But better that than not at all.
+        // This can end up being done twice. Better twice than not at all.
         invalidateValues();
     }
 
@@ -872,7 +890,7 @@
 
     private Alignment getAlignment(Alignment alignment, boolean horizontal) {
         return (alignment != UNDEFINED_ALIGNMENT) ? alignment :
-                (horizontal ? mColumnAlignment : mRowAlignment);
+                (horizontal ? LEFT : BASELINE);
     }
 
     // Layout container
@@ -970,6 +988,9 @@
 
             int cx = paddingLeft + x1 + dx;
             int cy = paddingTop + y1 + dy;
+            if (width != c.getMeasuredWidth() || height != c.getMeasuredHeight()) {
+                c.measure(makeMeasureSpec(width, EXACTLY), makeMeasureSpec(height, EXACTLY));
+            }
             c.layout(cx, cy, cx + width, cy + height);
         }
     }
@@ -1237,53 +1258,6 @@
             return topologicalSort(arcs.toArray(new Arc[arcs.size()]));
         }
 
-        private boolean[] findUsed(Collection<Arc> arcs) {
-            boolean[] result = new boolean[getCount()];
-            for (Arc arc : arcs) {
-                Interval span = arc.span;
-                int min = min(span.min, span.max);
-                int max = max(span.min, span.max);
-                for (int i = min; i < max; i++) {
-                    result[i] = true;
-                }
-            }
-            return result;
-        }
-
-        // todo unify with findUsed above. Both routines analyze which rows/columns are empty.
-        private Collection<Interval> getSpacers() {
-            List<Interval> result = new ArrayList<Interval>();
-            int V = getCount() + 1;
-            int[] leadingEdgeCount = new int[V];
-            int[] trailingEdgeCount = new int[V];
-            for (int i = 0, N = getChildCount(); i < N; i++) {
-                View c = getChildAt(i);
-                if (isGone(c)) continue;
-                LayoutParams lp = getLayoutParams(c);
-                Spec spec = horizontal ? lp.columnSpec : lp.rowSpec;
-                Interval span = spec.span;
-                leadingEdgeCount[span.min]++;
-                trailingEdgeCount[span.max]++;
-            }
-
-            int lastTrailingEdge = 0;
-
-            // treat the parent's edges like peer edges of the opposite type
-            trailingEdgeCount[0] = 1;
-            leadingEdgeCount[V - 1] = 1;
-
-            for (int i = 0; i < V; i++) {
-                if (trailingEdgeCount[i] > 0) {
-                    lastTrailingEdge = i;
-                    continue; // if this is also a leading edge, don't add a space of length zero
-                }
-                if (leadingEdgeCount[i] > 0) {
-                    result.add(new Interval(lastTrailingEdge, i));
-                }
-            }
-            return result;
-        }
-
         private void addComponentSizes(List<Arc> result, PackedMap<Interval, MutableInt> links) {
             for (int i = 0; i < links.keys.length; i++) {
                 Interval key = links.keys[i];
@@ -1300,28 +1274,11 @@
             // Add the maximum values from the components.
             addComponentSizes(maxs, getBackwardLinks());
 
-            // Find redundant rows/cols and glue them together with 0-length arcs to link the tree
-            boolean[] used = findUsed(mins);
-            for (int i = 0; i < getCount(); i++) {
-                if (!used[i]) {
-                    Interval span = new Interval(i, i + 1);
-                    include(mins, span, new MutableInt(0));
-                    include(maxs, span.inverse(), new MutableInt(0));
-                }
-            }
-
             // Add ordering constraints to prevent row/col sizes from going negative
             if (mOrderPreserved) {
                 // Add a constraint for every row/col
                 for (int i = 0; i < getCount(); i++) {
-                    if (used[i]) {
-                        include(mins, new Interval(i, i + 1), new MutableInt(0));
-                    }
-                }
-            } else {
-                // Add a constraint for each row/col that separates opposing component edges
-                for (Interval gap : getSpacers()) {
-                    include(mins, gap, new MutableInt(0));
+                    include(mins, new Interval(i, i + 1), new MutableInt(0));
                 }
             }
 
@@ -1658,10 +1615,8 @@
      *
      * @attr ref android.R.styleable#GridLayout_Layout_layout_row
      * @attr ref android.R.styleable#GridLayout_Layout_layout_rowSpan
-     * @attr ref android.R.styleable#GridLayout_Layout_layout_rowFlexibility
      * @attr ref android.R.styleable#GridLayout_Layout_layout_column
      * @attr ref android.R.styleable#GridLayout_Layout_layout_columnSpan
-     * @attr ref android.R.styleable#GridLayout_Layout_layout_columnFlexibility
      * @attr ref android.R.styleable#GridLayout_Layout_layout_gravity
      */
     public static class LayoutParams extends MarginLayoutParams {
@@ -1688,13 +1643,9 @@
 
         private static final int COLUMN = R.styleable.GridLayout_Layout_layout_column;
         private static final int COLUMN_SPAN = R.styleable.GridLayout_Layout_layout_columnSpan;
-        private static final int COLUMN_FLEXIBILITY =
-                R.styleable.GridLayout_Layout_layout_columnFlexibility;
 
         private static final int ROW = R.styleable.GridLayout_Layout_layout_row;
         private static final int ROW_SPAN = R.styleable.GridLayout_Layout_layout_rowSpan;
-        private static final int ROW_FLEXIBILITY =
-                R.styleable.GridLayout_Layout_layout_rowFlexibility;
 
         private static final int GRAVITY = R.styleable.GridLayout_Layout_layout_gravity;
 
@@ -1816,13 +1767,11 @@
 
                 int column = a.getInt(COLUMN, DEFAULT_COLUMN);
                 int colSpan = a.getInt(COLUMN_SPAN, DEFAULT_SPAN_SIZE);
-                int hFlexibility = a.getInt(COLUMN_FLEXIBILITY, Spec.UNDEFINED_FLEXIBILITY);
-                this.columnSpec = spec(column, colSpan, getAlignment(gravity, true), hFlexibility);
+                this.columnSpec = spec(column, colSpan, getAlignment(gravity, true));
 
                 int row = a.getInt(ROW, DEFAULT_ROW);
                 int rowSpan = a.getInt(ROW_SPAN, DEFAULT_SPAN_SIZE);
-                int vFlexibility = a.getInt(ROW_FLEXIBILITY, Spec.UNDEFINED_FLEXIBILITY);
-                this.rowSpec = spec(row, rowSpan, getAlignment(gravity, false), vFlexibility);
+                this.rowSpec = spec(row, rowSpan, getAlignment(gravity, false));
             } finally {
                 a.recycle();
             }
@@ -2150,19 +2099,19 @@
         }
     }
 
-   /**
-    * A Spec defines the horizontal or vertical characteristics of a group of
-    * cells. Each spec. defines the <em>grid indices</em>, <em>alignment</em> and
-    * <em>flexibility</em> along the appropriate axis.
-    * <p>
-    * The <em>grid indices</em> are the leading and trailing edges of this cell group.
-    * See {@link GridLayout} for a description of the conventions used by GridLayout
-    * for grid indices.
-    * <p>
-    * The <em>alignment</em> property specifies how cells should be aligned in this group.
-    * For row groups, this specifies the vertical alignment.
-    * For column groups, this specifies the horizontal alignment.
-    */
+    /**
+     * A Spec defines the horizontal or vertical characteristics of a group of
+     * cells. Each spec. defines the <em>grid indices</em>, <em>alignment</em> and
+     * <em>flexibility</em> along the appropriate axis.
+     * <p>
+     * The <em>grid indices</em> are the leading and trailing edges of this cell group.
+     * See {@link GridLayout} for a description of the conventions used by GridLayout
+     * for grid indices.
+     * <p>
+     * The <em>alignment</em> property specifies how cells should be aligned in this group.
+     * For row groups, this specifies the vertical alignment.
+     * For column groups, this specifies the horizontal alignment.
+     */
     public static class Spec {
         private static final int UNDEFINED_FLEXIBILITY = UNDEFINED;
 
@@ -2170,18 +2119,18 @@
 
         final Alignment alignment;
 
-     /**
-       * The <em>flexibility</em> property tells GridLayout how to derive minimum and maximum size
-       * values for a component. Specifications are made with respect to a child's
-       * 'measured size'. A child's measured size is, in turn, controlled by its
-       * height and width layout parameters which either specify a size or, in
-       * the case of {@link LayoutParams#WRAP_CONTENT WRAP_CONTENT}, defer to
-       * the computed size of the component.
-       * <p>
-       * A cell group is flexible only if <em>all</em> of its components are flexible.
-       * <p>
-       * By default, flexibility is {@link #INFLEXIBLE} only when alignment/gravity is undefined.
-       */
+        /**
+         * The <em>flexibility</em> property tells GridLayout how to derive minimum and maximum size
+         * values for a component. Specifications are made with respect to a child's
+         * 'measured size'. A child's measured size is, in turn, controlled by its
+         * height and width layout parameters which either specify a size or, in
+         * the case of {@link LayoutParams#WRAP_CONTENT WRAP_CONTENT}, defer to
+         * the computed size of the component.
+         * <p>
+         * A cell group is flexible only if <em>all</em> of its components are flexible.
+         * <p>
+         * By default, flexibility is {@link #INFLEXIBLE} only when alignment/gravity is undefined.
+         */
         final int flexibility;
 
         private Spec(Interval span, Alignment alignment, int flexibility) {
@@ -2190,17 +2139,13 @@
             this.flexibility = flexibility;
         }
 
-        private Spec(Interval span, Alignment alignment) {
-            this(span, alignment, UNDEFINED_FLEXIBILITY);
-        }
-
         /* Copying constructor */
         private Spec(Spec that) {
             this(that.span, that.alignment, that.flexibility);
         }
 
-        Spec(int start, int size, Alignment alignment, int flexibility) {
-            this(new Interval(start, start + size), alignment, flexibility);
+        private Spec(int start, int size, Alignment alignment) {
+            this(new Interval(start, start + size), alignment, UNDEFINED);
         }
 
         private Spec copyWriteSpan(Interval span) {
@@ -2261,28 +2206,6 @@
     }
 
     /**
-     * @deprecated Please use {@link #spec(int, int, Alignment)} instead,
-     * all spec's that define alignments (gravity) are  assumed to be able to stretch.
-     *
-     * @hide
-     */
-    @Deprecated
-    public static Spec spec(int start, int size, Alignment alignment, int flexibility) {
-        return new Spec(start, size, alignment, flexibility);
-    }
-
-    /**
-     * @deprecated Please use {@link #spec(int, Alignment)} instead,
-     * all spec's that define alignments (gravity) are assumed to be able to stretch.
-     *
-     * @hide
-     */
-    @Deprecated
-    public static Spec spec(int start, Alignment alignment, int flexibility) {
-        return spec(start, 1, alignment, flexibility);
-    }
-
-    /**
      * Return a Spec, {@code spec}, where:
      * <ul>
      *     <li> {@code spec.span = [start, start + size]} </li>
@@ -2294,7 +2217,7 @@
      * @param alignment the alignment
      */
     public static Spec spec(int start, int size, Alignment alignment) {
-        return spec(start, size, alignment, Spec.UNDEFINED_FLEXIBILITY);
+        return new Spec(start, size, alignment);
     }
 
     /**
diff --git a/core/res/res/values/attrs.xml b/core/res/res/values/attrs.xml
index f80f27d..f70319b 100755
--- a/core/res/res/values/attrs.xml
+++ b/core/res/res/values/attrs.xml
@@ -2632,12 +2632,12 @@
         <attr name="alignmentMode" />
         <!-- When set to true, forces row boundaries to appear in the same order
         as row indices.
-        The default is false.
+        The default is true.
         See {@link android.widget.GridLayout#setRowOrderPreserved(boolean)}.-->
         <attr name="rowOrderPreserved" format="boolean" />
         <!-- When set to true, forces column boundaries to appear in the same order
         as column indices.
-        The default is false.
+        The default is true.
         See {@link android.widget.GridLayout#setColumnOrderPreserved(boolean)}.-->
         <attr name="columnOrderPreserved" format="boolean" />
     </declare-styleable>
@@ -3363,18 +3363,6 @@
         The default is LEFT | BASELINE.
         See {@link android.widget.GridLayout.LayoutParams#setGravity(int)}. -->
         <attr name="layout_gravity" />
-        <!-- {@deprecated To make a column group lexible, ensure that every component in the
-         group defines a horizontal gravity.} -->
-        <attr name="layout_columnFlexibility" >
-            <enum name="inflexible" value="0" />
-            <enum name="canStretch" value="2" />
-        </attr>
-        <!-- {@deprecated To make a row group flexible, ensure that every component in the
-         group defines a vertical gravity.} -->
-        <attr name="layout_rowFlexibility" >
-            <enum name="inflexible" value="0" />
-            <enum name="canStretch" value="2" />
-        </attr>
     </declare-styleable>
     <declare-styleable name="FrameLayout_Layout">
         <attr name="layout_gravity" />
diff --git a/core/res/res/values/public.xml b/core/res/res/values/public.xml
index 0555d10..87e9249 100644
--- a/core/res/res/values/public.xml
+++ b/core/res/res/values/public.xml
@@ -1728,10 +1728,8 @@
 
   <public type="attr" name="layout_row" />
   <public type="attr" name="layout_rowSpan" />
-  <public type="attr" name="layout_rowFlexibility" />
 
   <public type="attr" name="layout_columnSpan" />
-  <public type="attr" name="layout_columnFlexibility" />
 
   <public type="attr" name="actionModeSelectAllDrawable" />
 
diff --git a/tests/GridLayoutTest/src/com/android/test/layout/Activity2.java b/tests/GridLayoutTest/src/com/android/test/layout/Activity2.java
index e1871ac..907ee9c 100644
--- a/tests/GridLayoutTest/src/com/android/test/layout/Activity2.java
+++ b/tests/GridLayoutTest/src/com/android/test/layout/Activity2.java
@@ -34,15 +34,17 @@
 public class Activity2 extends Activity {
 
     public static View create(Context context) {
-        GridLayout vg = new GridLayout(context);
-        vg.setUseDefaultMargins(true);
-        vg.setAlignmentMode(ALIGN_BOUNDS);
+        GridLayout p = new GridLayout(context);
+        p.setUseDefaultMargins(true);
+        p.setAlignmentMode(ALIGN_BOUNDS);
+        p.setRowOrderPreserved(false);
+        p.setPadding(0, 0, 0, 0);
 
         Spec row1 = spec(0);
         Spec row2 = spec(1);
         Spec row3 = spec(2, BASELINE);
         Spec row4 = spec(3, BASELINE);
-        Spec row5 = spec(4, FILL);
+        Spec row5 = spec(2, 3, FILL); // allow the last two rows to overlap the middle two
         Spec row6 = spec(5);
         Spec row7 = spec(6);
 
@@ -55,63 +57,63 @@
         Spec col4b = spec(3, FILL);
 
         {
-            TextView v = new TextView(context);
-            v.setTextSize(32);
-            v.setText("Email setup");
-            vg.addView(v, new LayoutParams(row1, col1a));
+            TextView c = new TextView(context);
+            c.setTextSize(32);
+            c.setText("Email setup");
+            p.addView(c, new LayoutParams(row1, col1a));
         }
         {
-            TextView v = new TextView(context);
-            v.setTextSize(16);
-            v.setText("You can configure email in just a few steps:");
-            vg.addView(v, new LayoutParams(row2, col1b));
+            TextView c = new TextView(context);
+            c.setTextSize(16);
+            c.setText("You can configure email in just a few steps:");
+            p.addView(c, new LayoutParams(row2, col1b));
         }
         {
-            TextView v = new TextView(context);
-            v.setText("Email address:");
-            vg.addView(v, new LayoutParams(row3, col1c));
+            TextView c = new TextView(context);
+            c.setText("Email address:");
+            p.addView(c, new LayoutParams(row3, col1c));
         }
         {
-            EditText v = new EditText(context);
-            v.setInputType(TYPE_CLASS_TEXT | TYPE_TEXT_VARIATION_EMAIL_ADDRESS);
+            EditText c = new EditText(context);
+            c.setInputType(TYPE_CLASS_TEXT | TYPE_TEXT_VARIATION_EMAIL_ADDRESS);
             {
                 LayoutParams lp = new LayoutParams(row3, col2);
-                lp.width = (int) v.getPaint().measureText("Frederick.W.Flintstone");
-                vg.addView(v, lp);
+                lp.width = (int) c.getPaint().measureText("Frederick.W.Flintstone");
+                p.addView(c, lp);
             }
         }
         {
-            TextView v = new TextView(context);
-            v.setText("Password:");
-            vg.addView(v, new LayoutParams(row4, col1c));
+            TextView c = new TextView(context);
+            c.setText("Password:");
+            p.addView(c, new LayoutParams(row4, col1c));
         }
         {
-            TextView v = new EditText(context);
-            v.setInputType(TYPE_CLASS_TEXT | TYPE_TEXT_VARIATION_PASSWORD);
+            TextView c = new EditText(context);
+            c.setInputType(TYPE_CLASS_TEXT | TYPE_TEXT_VARIATION_PASSWORD);
             {
                 LayoutParams lp = new LayoutParams(row4, col2);
-                lp.width = (int) v.getPaint().measureText("************");
-                vg.addView(v, lp);
+                lp.width = (int) c.getPaint().measureText("************");
+                p.addView(c, lp);
             }
         }
         {
-            Space v = new Space(context);
+            Space c = new Space(context);
             LayoutParams lp = new LayoutParams(row5, col3);
             lp.setMargins(0, 0, 0, 0);
-            vg.addView(v, lp);
+            p.addView(c, lp);
         }
         {
-            Button v = new Button(context);
-            v.setText("Manual setup");
-            vg.addView(v, new LayoutParams(row6, col4a));
+            Button c = new Button(context);
+            c.setText("Manual setup");
+            p.addView(c, new LayoutParams(row6, col4a));
         }
         {
-            Button v = new Button(context);
-            v.setText("Next");
-            vg.addView(v, new LayoutParams(row7, col4b));
+            Button c = new Button(context);
+            c.setText("Next");
+            p.addView(c, new LayoutParams(row7, col4b));
         }
 
-        return vg;
+        return p;
     }
 
     protected void onCreate(Bundle savedInstanceState) {