2 * Copyright (C) 2006 The Android Open Source Project
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
8 * http://www.apache.org/licenses/LICENSE-2.0
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
17 package android.widget;
19 import com.android.internal.R;
21 import android.content.Context;
22 import android.content.res.TypedArray;
23 import android.content.res.Resources;
24 import android.graphics.Rect;
25 import android.util.AttributeSet;
26 import android.util.SparseArray;
27 import android.util.Poolable;
28 import android.util.Pool;
29 import android.util.Pools;
30 import android.util.PoolableManager;
31 import static android.util.Log.d;
32 import android.view.Gravity;
33 import android.view.View;
34 import android.view.ViewDebug;
35 import android.view.ViewGroup;
36 import android.view.accessibility.AccessibilityEvent;
37 import android.widget.RemoteViews.RemoteView;
39 import java.util.Comparator;
40 import java.util.SortedSet;
41 import java.util.TreeSet;
42 import java.util.LinkedList;
43 import java.util.HashSet;
44 import java.util.ArrayList;
47 * A Layout where the positions of the children can be described in relation to each other or to the
51 * Note that you cannot have a circular dependency between the size of the RelativeLayout and the
52 * position of its children. For example, you cannot have a RelativeLayout whose height is set to
53 * {@link android.view.ViewGroup.LayoutParams#WRAP_CONTENT WRAP_CONTENT} and a child set to
54 * {@link #ALIGN_PARENT_BOTTOM}.
57 * <p>See the <a href="{@docRoot}resources/tutorials/views/hello-relativelayout.html">Relative
58 * Layout tutorial</a>.</p>
61 * Also see {@link android.widget.RelativeLayout.LayoutParams RelativeLayout.LayoutParams} for
65 * @attr ref android.R.styleable#RelativeLayout_gravity
66 * @attr ref android.R.styleable#RelativeLayout_ignoreGravity
69 public class RelativeLayout extends ViewGroup {
70 private static final String LOG_TAG = "RelativeLayout";
72 private static final boolean DEBUG_GRAPH = false;
74 public static final int TRUE = -1;
77 * Rule that aligns a child's right edge with another child's left edge.
79 public static final int LEFT_OF = 0;
81 * Rule that aligns a child's left edge with another child's right edge.
83 public static final int RIGHT_OF = 1;
85 * Rule that aligns a child's bottom edge with another child's top edge.
87 public static final int ABOVE = 2;
89 * Rule that aligns a child's top edge with another child's bottom edge.
91 public static final int BELOW = 3;
94 * Rule that aligns a child's baseline with another child's baseline.
96 public static final int ALIGN_BASELINE = 4;
98 * Rule that aligns a child's left edge with another child's left edge.
100 public static final int ALIGN_LEFT = 5;
102 * Rule that aligns a child's top edge with another child's top edge.
104 public static final int ALIGN_TOP = 6;
106 * Rule that aligns a child's right edge with another child's right edge.
108 public static final int ALIGN_RIGHT = 7;
110 * Rule that aligns a child's bottom edge with another child's bottom edge.
112 public static final int ALIGN_BOTTOM = 8;
115 * Rule that aligns the child's left edge with its RelativeLayout
116 * parent's left edge.
118 public static final int ALIGN_PARENT_LEFT = 9;
120 * Rule that aligns the child's top edge with its RelativeLayout
123 public static final int ALIGN_PARENT_TOP = 10;
125 * Rule that aligns the child's right edge with its RelativeLayout
126 * parent's right edge.
128 public static final int ALIGN_PARENT_RIGHT = 11;
130 * Rule that aligns the child's bottom edge with its RelativeLayout
131 * parent's bottom edge.
133 public static final int ALIGN_PARENT_BOTTOM = 12;
136 * Rule that centers the child with respect to the bounds of its
137 * RelativeLayout parent.
139 public static final int CENTER_IN_PARENT = 13;
141 * Rule that centers the child horizontally with respect to the
142 * bounds of its RelativeLayout parent.
144 public static final int CENTER_HORIZONTAL = 14;
146 * Rule that centers the child vertically with respect to the
147 * bounds of its RelativeLayout parent.
149 public static final int CENTER_VERTICAL = 15;
151 private static final int VERB_COUNT = 16;
153 private View mBaselineView = null;
154 private boolean mHasBaselineAlignedChild;
156 private int mGravity = Gravity.LEFT | Gravity.TOP;
157 private final Rect mContentBounds = new Rect();
158 private final Rect mSelfBounds = new Rect();
159 private int mIgnoreGravity;
161 private SortedSet<View> mTopToBottomLeftToRightSet = null;
163 private boolean mDirtyHierarchy;
164 private View[] mSortedHorizontalChildren = new View[0];
165 private View[] mSortedVerticalChildren = new View[0];
166 private final DependencyGraph mGraph = new DependencyGraph();
168 public RelativeLayout(Context context) {
172 public RelativeLayout(Context context, AttributeSet attrs) {
173 super(context, attrs);
174 initFromAttributes(context, attrs);
177 public RelativeLayout(Context context, AttributeSet attrs, int defStyle) {
178 super(context, attrs, defStyle);
179 initFromAttributes(context, attrs);
182 private void initFromAttributes(Context context, AttributeSet attrs) {
183 TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.RelativeLayout);
184 mIgnoreGravity = a.getResourceId(R.styleable.RelativeLayout_ignoreGravity, View.NO_ID);
185 mGravity = a.getInt(R.styleable.RelativeLayout_gravity, mGravity);
190 * Defines which View is ignored when the gravity is applied. This setting has no
191 * effect if the gravity is <code>Gravity.LEFT | Gravity.TOP</code>.
193 * @param viewId The id of the View to be ignored by gravity, or 0 if no View
196 * @see #setGravity(int)
198 * @attr ref android.R.styleable#RelativeLayout_ignoreGravity
200 @android.view.RemotableViewMethod
201 public void setIgnoreGravity(int viewId) {
202 mIgnoreGravity = viewId;
206 * Describes how the child views are positioned. Defaults to
207 * <code>Gravity.LEFT | Gravity.TOP</code>.
209 * @param gravity See {@link android.view.Gravity}
211 * @see #setHorizontalGravity(int)
212 * @see #setVerticalGravity(int)
214 * @attr ref android.R.styleable#RelativeLayout_gravity
216 @android.view.RemotableViewMethod
217 public void setGravity(int gravity) {
218 if (mGravity != gravity) {
219 if ((gravity & Gravity.HORIZONTAL_GRAVITY_MASK) == 0) {
220 gravity |= Gravity.LEFT;
223 if ((gravity & Gravity.VERTICAL_GRAVITY_MASK) == 0) {
224 gravity |= Gravity.TOP;
232 @android.view.RemotableViewMethod
233 public void setHorizontalGravity(int horizontalGravity) {
234 final int gravity = horizontalGravity & Gravity.HORIZONTAL_GRAVITY_MASK;
235 if ((mGravity & Gravity.HORIZONTAL_GRAVITY_MASK) != gravity) {
236 mGravity = (mGravity & ~Gravity.HORIZONTAL_GRAVITY_MASK) | gravity;
241 @android.view.RemotableViewMethod
242 public void setVerticalGravity(int verticalGravity) {
243 final int gravity = verticalGravity & Gravity.VERTICAL_GRAVITY_MASK;
244 if ((mGravity & Gravity.VERTICAL_GRAVITY_MASK) != gravity) {
245 mGravity = (mGravity & ~Gravity.VERTICAL_GRAVITY_MASK) | gravity;
251 public int getBaseline() {
252 return mBaselineView != null ? mBaselineView.getBaseline() : super.getBaseline();
256 public void requestLayout() {
257 super.requestLayout();
258 mDirtyHierarchy = true;
261 private void sortChildren() {
262 int count = getChildCount();
263 if (mSortedVerticalChildren.length != count) mSortedVerticalChildren = new View[count];
264 if (mSortedHorizontalChildren.length != count) mSortedHorizontalChildren = new View[count];
266 final DependencyGraph graph = mGraph;
269 for (int i = 0; i < count; i++) {
270 final View child = getChildAt(i);
275 d(LOG_TAG, "=== Sorted vertical children");
276 graph.log(getResources(), ABOVE, BELOW, ALIGN_BASELINE, ALIGN_TOP, ALIGN_BOTTOM);
277 d(LOG_TAG, "=== Sorted horizontal children");
278 graph.log(getResources(), LEFT_OF, RIGHT_OF, ALIGN_LEFT, ALIGN_RIGHT);
281 graph.getSortedViews(mSortedVerticalChildren, ABOVE, BELOW, ALIGN_BASELINE,
282 ALIGN_TOP, ALIGN_BOTTOM);
283 graph.getSortedViews(mSortedHorizontalChildren, LEFT_OF, RIGHT_OF, ALIGN_LEFT, ALIGN_RIGHT);
286 d(LOG_TAG, "=== Ordered list of vertical children");
287 for (View view : mSortedVerticalChildren) {
288 DependencyGraph.printViewId(getResources(), view);
290 d(LOG_TAG, "=== Ordered list of horizontal children");
291 for (View view : mSortedHorizontalChildren) {
292 DependencyGraph.printViewId(getResources(), view);
297 // TODO: we need to find another way to implement RelativeLayout
298 // This implementation cannot handle every case
300 protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
301 if (mDirtyHierarchy) {
302 mDirtyHierarchy = false;
312 int widthMode = MeasureSpec.getMode(widthMeasureSpec);
313 int heightMode = MeasureSpec.getMode(heightMeasureSpec);
314 int widthSize = MeasureSpec.getSize(widthMeasureSpec);
315 int heightSize = MeasureSpec.getSize(heightMeasureSpec);
317 // Record our dimensions if they are known;
318 if (widthMode != MeasureSpec.UNSPECIFIED) {
322 if (heightMode != MeasureSpec.UNSPECIFIED) {
323 myHeight = heightSize;
326 if (widthMode == MeasureSpec.EXACTLY) {
330 if (heightMode == MeasureSpec.EXACTLY) {
334 mHasBaselineAlignedChild = false;
337 int gravity = mGravity & Gravity.HORIZONTAL_GRAVITY_MASK;
338 final boolean horizontalGravity = gravity != Gravity.LEFT && gravity != 0;
339 gravity = mGravity & Gravity.VERTICAL_GRAVITY_MASK;
340 final boolean verticalGravity = gravity != Gravity.TOP && gravity != 0;
342 int left = Integer.MAX_VALUE;
343 int top = Integer.MAX_VALUE;
344 int right = Integer.MIN_VALUE;
345 int bottom = Integer.MIN_VALUE;
347 boolean offsetHorizontalAxis = false;
348 boolean offsetVerticalAxis = false;
350 if ((horizontalGravity || verticalGravity) && mIgnoreGravity != View.NO_ID) {
351 ignore = findViewById(mIgnoreGravity);
354 final boolean isWrapContentWidth = widthMode != MeasureSpec.EXACTLY;
355 final boolean isWrapContentHeight = heightMode != MeasureSpec.EXACTLY;
357 View[] views = mSortedHorizontalChildren;
358 int count = views.length;
359 for (int i = 0; i < count; i++) {
360 View child = views[i];
361 if (child.getVisibility() != GONE) {
362 LayoutParams params = (LayoutParams) child.getLayoutParams();
364 applyHorizontalSizeRules(params, myWidth);
365 measureChildHorizontal(child, params, myWidth, myHeight);
366 if (positionChildHorizontal(child, params, myWidth, isWrapContentWidth)) {
367 offsetHorizontalAxis = true;
372 views = mSortedVerticalChildren;
373 count = views.length;
375 for (int i = 0; i < count; i++) {
376 View child = views[i];
377 if (child.getVisibility() != GONE) {
378 LayoutParams params = (LayoutParams) child.getLayoutParams();
380 applyVerticalSizeRules(params, myHeight);
381 measureChild(child, params, myWidth, myHeight);
382 if (positionChildVertical(child, params, myHeight, isWrapContentHeight)) {
383 offsetVerticalAxis = true;
386 if (isWrapContentWidth) {
387 width = Math.max(width, params.mRight);
390 if (isWrapContentHeight) {
391 height = Math.max(height, params.mBottom);
394 if (child != ignore || verticalGravity) {
395 left = Math.min(left, params.mLeft - params.leftMargin);
396 top = Math.min(top, params.mTop - params.topMargin);
399 if (child != ignore || horizontalGravity) {
400 right = Math.max(right, params.mRight + params.rightMargin);
401 bottom = Math.max(bottom, params.mBottom + params.bottomMargin);
406 if (mHasBaselineAlignedChild) {
407 for (int i = 0; i < count; i++) {
408 View child = getChildAt(i);
409 if (child.getVisibility() != GONE) {
410 LayoutParams params = (LayoutParams) child.getLayoutParams();
411 alignBaseline(child, params);
413 if (child != ignore || verticalGravity) {
414 left = Math.min(left, params.mLeft - params.leftMargin);
415 top = Math.min(top, params.mTop - params.topMargin);
418 if (child != ignore || horizontalGravity) {
419 right = Math.max(right, params.mRight + params.rightMargin);
420 bottom = Math.max(bottom, params.mBottom + params.bottomMargin);
426 if (isWrapContentWidth) {
427 // Width already has left padding in it since it was calculated by looking at
428 // the right of each child view
429 width += mPaddingRight;
431 if (mLayoutParams.width >= 0) {
432 width = Math.max(width, mLayoutParams.width);
435 width = Math.max(width, getSuggestedMinimumWidth());
436 width = resolveSize(width, widthMeasureSpec);
438 if (offsetHorizontalAxis) {
439 for (int i = 0; i < count; i++) {
440 View child = getChildAt(i);
441 if (child.getVisibility() != GONE) {
442 LayoutParams params = (LayoutParams) child.getLayoutParams();
443 final int[] rules = params.getRules();
444 if (rules[CENTER_IN_PARENT] != 0 || rules[CENTER_HORIZONTAL] != 0) {
445 centerHorizontal(child, params, width);
446 } else if (rules[ALIGN_PARENT_RIGHT] != 0) {
447 final int childWidth = child.getMeasuredWidth();
448 params.mLeft = width - mPaddingRight - childWidth;
449 params.mRight = params.mLeft + childWidth;
456 if (isWrapContentHeight) {
457 // Height already has top padding in it since it was calculated by looking at
458 // the bottom of each child view
459 height += mPaddingBottom;
461 if (mLayoutParams.height >= 0) {
462 height = Math.max(height, mLayoutParams.height);
465 height = Math.max(height, getSuggestedMinimumHeight());
466 height = resolveSize(height, heightMeasureSpec);
468 if (offsetVerticalAxis) {
469 for (int i = 0; i < count; i++) {
470 View child = getChildAt(i);
471 if (child.getVisibility() != GONE) {
472 LayoutParams params = (LayoutParams) child.getLayoutParams();
473 final int[] rules = params.getRules();
474 if (rules[CENTER_IN_PARENT] != 0 || rules[CENTER_VERTICAL] != 0) {
475 centerVertical(child, params, height);
476 } else if (rules[ALIGN_PARENT_BOTTOM] != 0) {
477 final int childHeight = child.getMeasuredHeight();
478 params.mTop = height - mPaddingBottom - childHeight;
479 params.mBottom = params.mTop + childHeight;
486 if (horizontalGravity || verticalGravity) {
487 final Rect selfBounds = mSelfBounds;
488 selfBounds.set(mPaddingLeft, mPaddingTop, width - mPaddingRight,
489 height - mPaddingBottom);
491 final Rect contentBounds = mContentBounds;
492 Gravity.apply(mGravity, right - left, bottom - top, selfBounds, contentBounds);
494 final int horizontalOffset = contentBounds.left - left;
495 final int verticalOffset = contentBounds.top - top;
496 if (horizontalOffset != 0 || verticalOffset != 0) {
497 for (int i = 0; i < count; i++) {
498 View child = getChildAt(i);
499 if (child.getVisibility() != GONE && child != ignore) {
500 LayoutParams params = (LayoutParams) child.getLayoutParams();
501 if (horizontalGravity) {
502 params.mLeft += horizontalOffset;
503 params.mRight += horizontalOffset;
505 if (verticalGravity) {
506 params.mTop += verticalOffset;
507 params.mBottom += verticalOffset;
514 setMeasuredDimension(width, height);
517 private void alignBaseline(View child, LayoutParams params) {
518 int[] rules = params.getRules();
519 int anchorBaseline = getRelatedViewBaseline(rules, ALIGN_BASELINE);
521 if (anchorBaseline != -1) {
522 LayoutParams anchorParams = getRelatedViewParams(rules, ALIGN_BASELINE);
523 if (anchorParams != null) {
524 int offset = anchorParams.mTop + anchorBaseline;
525 int baseline = child.getBaseline();
526 if (baseline != -1) {
529 int height = params.mBottom - params.mTop;
530 params.mTop = offset;
531 params.mBottom = params.mTop + height;
535 if (mBaselineView == null) {
536 mBaselineView = child;
538 LayoutParams lp = (LayoutParams) mBaselineView.getLayoutParams();
539 if (params.mTop < lp.mTop || (params.mTop == lp.mTop && params.mLeft < lp.mLeft)) {
540 mBaselineView = child;
546 * Measure a child. The child should have left, top, right and bottom information
547 * stored in its LayoutParams. If any of these values is -1 it means that the view
548 * can extend up to the corresponding edge.
550 * @param child Child to measure
551 * @param params LayoutParams associated with child
552 * @param myWidth Width of the the RelativeLayout
553 * @param myHeight Height of the RelativeLayout
555 private void measureChild(View child, LayoutParams params, int myWidth, int myHeight) {
556 int childWidthMeasureSpec = getChildMeasureSpec(params.mLeft,
557 params.mRight, params.width,
558 params.leftMargin, params.rightMargin,
559 mPaddingLeft, mPaddingRight,
561 int childHeightMeasureSpec = getChildMeasureSpec(params.mTop,
562 params.mBottom, params.height,
563 params.topMargin, params.bottomMargin,
564 mPaddingTop, mPaddingBottom,
566 child.measure(childWidthMeasureSpec, childHeightMeasureSpec);
569 private void measureChildHorizontal(View child, LayoutParams params, int myWidth, int myHeight) {
570 int childWidthMeasureSpec = getChildMeasureSpec(params.mLeft,
571 params.mRight, params.width,
572 params.leftMargin, params.rightMargin,
573 mPaddingLeft, mPaddingRight,
575 int childHeightMeasureSpec;
576 if (params.width == LayoutParams.MATCH_PARENT) {
577 childHeightMeasureSpec = MeasureSpec.makeMeasureSpec(myHeight, MeasureSpec.EXACTLY);
579 childHeightMeasureSpec = MeasureSpec.makeMeasureSpec(myHeight, MeasureSpec.AT_MOST);
581 child.measure(childWidthMeasureSpec, childHeightMeasureSpec);
585 * Get a measure spec that accounts for all of the constraints on this view.
586 * This includes size contstraints imposed by the RelativeLayout as well as
587 * the View's desired dimension.
589 * @param childStart The left or top field of the child's layout params
590 * @param childEnd The right or bottom field of the child's layout params
591 * @param childSize The child's desired size (the width or height field of
592 * the child's layout params)
593 * @param startMargin The left or top margin
594 * @param endMargin The right or bottom margin
595 * @param startPadding mPaddingLeft or mPaddingTop
596 * @param endPadding mPaddingRight or mPaddingBottom
597 * @param mySize The width or height of this view (the RelativeLayout)
598 * @return MeasureSpec for the child
600 private int getChildMeasureSpec(int childStart, int childEnd,
601 int childSize, int startMargin, int endMargin, int startPadding,
602 int endPadding, int mySize) {
603 int childSpecMode = 0;
604 int childSpecSize = 0;
606 // Figure out start and end bounds.
607 int tempStart = childStart;
608 int tempEnd = childEnd;
610 // If the view did not express a layout constraint for an edge, use
611 // view's margins and our padding
613 tempStart = startPadding + startMargin;
616 tempEnd = mySize - endPadding - endMargin;
619 // Figure out maximum size available to this view
620 int maxAvailable = tempEnd - tempStart;
622 if (childStart >= 0 && childEnd >= 0) {
623 // Constraints fixed both edges, so child must be an exact size
624 childSpecMode = MeasureSpec.EXACTLY;
625 childSpecSize = maxAvailable;
627 if (childSize >= 0) {
628 // Child wanted an exact size. Give as much as possible
629 childSpecMode = MeasureSpec.EXACTLY;
631 if (maxAvailable >= 0) {
632 // We have a maxmum size in this dimension.
633 childSpecSize = Math.min(maxAvailable, childSize);
635 // We can grow in this dimension.
636 childSpecSize = childSize;
638 } else if (childSize == LayoutParams.MATCH_PARENT) {
639 // Child wanted to be as big as possible. Give all availble
641 childSpecMode = MeasureSpec.EXACTLY;
642 childSpecSize = maxAvailable;
643 } else if (childSize == LayoutParams.WRAP_CONTENT) {
644 // Child wants to wrap content. Use AT_MOST
645 // to communicate available space if we know
647 if (maxAvailable >= 0) {
648 // We have a maxmum size in this dimension.
649 childSpecMode = MeasureSpec.AT_MOST;
650 childSpecSize = maxAvailable;
652 // We can grow in this dimension. Child can be as big as it
654 childSpecMode = MeasureSpec.UNSPECIFIED;
660 return MeasureSpec.makeMeasureSpec(childSpecSize, childSpecMode);
663 private boolean positionChildHorizontal(View child, LayoutParams params, int myWidth,
664 boolean wrapContent) {
666 int[] rules = params.getRules();
668 if (params.mLeft < 0 && params.mRight >= 0) {
669 // Right is fixed, but left varies
670 params.mLeft = params.mRight - child.getMeasuredWidth();
671 } else if (params.mLeft >= 0 && params.mRight < 0) {
672 // Left is fixed, but right varies
673 params.mRight = params.mLeft + child.getMeasuredWidth();
674 } else if (params.mLeft < 0 && params.mRight < 0) {
675 // Both left and right vary
676 if (rules[CENTER_IN_PARENT] != 0 || rules[CENTER_HORIZONTAL] != 0) {
678 centerHorizontal(child, params, myWidth);
680 params.mLeft = mPaddingLeft + params.leftMargin;
681 params.mRight = params.mLeft + child.getMeasuredWidth();
685 params.mLeft = mPaddingLeft + params.leftMargin;
686 params.mRight = params.mLeft + child.getMeasuredWidth();
689 return rules[ALIGN_PARENT_RIGHT] != 0;
692 private boolean positionChildVertical(View child, LayoutParams params, int myHeight,
693 boolean wrapContent) {
695 int[] rules = params.getRules();
697 if (params.mTop < 0 && params.mBottom >= 0) {
698 // Bottom is fixed, but top varies
699 params.mTop = params.mBottom - child.getMeasuredHeight();
700 } else if (params.mTop >= 0 && params.mBottom < 0) {
701 // Top is fixed, but bottom varies
702 params.mBottom = params.mTop + child.getMeasuredHeight();
703 } else if (params.mTop < 0 && params.mBottom < 0) {
704 // Both top and bottom vary
705 if (rules[CENTER_IN_PARENT] != 0 || rules[CENTER_VERTICAL] != 0) {
707 centerVertical(child, params, myHeight);
709 params.mTop = mPaddingTop + params.topMargin;
710 params.mBottom = params.mTop + child.getMeasuredHeight();
714 params.mTop = mPaddingTop + params.topMargin;
715 params.mBottom = params.mTop + child.getMeasuredHeight();
718 return rules[ALIGN_PARENT_BOTTOM] != 0;
721 private void applyHorizontalSizeRules(LayoutParams childParams, int myWidth) {
722 int[] rules = childParams.getRules();
723 RelativeLayout.LayoutParams anchorParams;
725 // -1 indicated a "soft requirement" in that direction. For example:
726 // left=10, right=-1 means the view must start at 10, but can go as far as it wants to the right
727 // left =-1, right=10 means the view must end at 10, but can go as far as it wants to the left
728 // left=10, right=20 means the left and right ends are both fixed
729 childParams.mLeft = -1;
730 childParams.mRight = -1;
732 anchorParams = getRelatedViewParams(rules, LEFT_OF);
733 if (anchorParams != null) {
734 childParams.mRight = anchorParams.mLeft - (anchorParams.leftMargin +
735 childParams.rightMargin);
736 } else if (childParams.alignWithParent && rules[LEFT_OF] != 0) {
738 childParams.mRight = myWidth - mPaddingRight - childParams.rightMargin;
744 anchorParams = getRelatedViewParams(rules, RIGHT_OF);
745 if (anchorParams != null) {
746 childParams.mLeft = anchorParams.mRight + (anchorParams.rightMargin +
747 childParams.leftMargin);
748 } else if (childParams.alignWithParent && rules[RIGHT_OF] != 0) {
749 childParams.mLeft = mPaddingLeft + childParams.leftMargin;
752 anchorParams = getRelatedViewParams(rules, ALIGN_LEFT);
753 if (anchorParams != null) {
754 childParams.mLeft = anchorParams.mLeft + childParams.leftMargin;
755 } else if (childParams.alignWithParent && rules[ALIGN_LEFT] != 0) {
756 childParams.mLeft = mPaddingLeft + childParams.leftMargin;
759 anchorParams = getRelatedViewParams(rules, ALIGN_RIGHT);
760 if (anchorParams != null) {
761 childParams.mRight = anchorParams.mRight - childParams.rightMargin;
762 } else if (childParams.alignWithParent && rules[ALIGN_RIGHT] != 0) {
764 childParams.mRight = myWidth - mPaddingRight - childParams.rightMargin;
770 if (0 != rules[ALIGN_PARENT_LEFT]) {
771 childParams.mLeft = mPaddingLeft + childParams.leftMargin;
774 if (0 != rules[ALIGN_PARENT_RIGHT]) {
776 childParams.mRight = myWidth - mPaddingRight - childParams.rightMargin;
783 private void applyVerticalSizeRules(LayoutParams childParams, int myHeight) {
784 int[] rules = childParams.getRules();
785 RelativeLayout.LayoutParams anchorParams;
787 childParams.mTop = -1;
788 childParams.mBottom = -1;
790 anchorParams = getRelatedViewParams(rules, ABOVE);
791 if (anchorParams != null) {
792 childParams.mBottom = anchorParams.mTop - (anchorParams.topMargin +
793 childParams.bottomMargin);
794 } else if (childParams.alignWithParent && rules[ABOVE] != 0) {
796 childParams.mBottom = myHeight - mPaddingBottom - childParams.bottomMargin;
802 anchorParams = getRelatedViewParams(rules, BELOW);
803 if (anchorParams != null) {
804 childParams.mTop = anchorParams.mBottom + (anchorParams.bottomMargin +
805 childParams.topMargin);
806 } else if (childParams.alignWithParent && rules[BELOW] != 0) {
807 childParams.mTop = mPaddingTop + childParams.topMargin;
810 anchorParams = getRelatedViewParams(rules, ALIGN_TOP);
811 if (anchorParams != null) {
812 childParams.mTop = anchorParams.mTop + childParams.topMargin;
813 } else if (childParams.alignWithParent && rules[ALIGN_TOP] != 0) {
814 childParams.mTop = mPaddingTop + childParams.topMargin;
817 anchorParams = getRelatedViewParams(rules, ALIGN_BOTTOM);
818 if (anchorParams != null) {
819 childParams.mBottom = anchorParams.mBottom - childParams.bottomMargin;
820 } else if (childParams.alignWithParent && rules[ALIGN_BOTTOM] != 0) {
822 childParams.mBottom = myHeight - mPaddingBottom - childParams.bottomMargin;
828 if (0 != rules[ALIGN_PARENT_TOP]) {
829 childParams.mTop = mPaddingTop + childParams.topMargin;
832 if (0 != rules[ALIGN_PARENT_BOTTOM]) {
834 childParams.mBottom = myHeight - mPaddingBottom - childParams.bottomMargin;
840 if (rules[ALIGN_BASELINE] != 0) {
841 mHasBaselineAlignedChild = true;
845 private View getRelatedView(int[] rules, int relation) {
846 int id = rules[relation];
848 DependencyGraph.Node node = mGraph.mKeyNodes.get(id);
849 if (node == null) return null;
852 // Find the first non-GONE view up the chain
853 while (v.getVisibility() == View.GONE) {
854 rules = ((LayoutParams) v.getLayoutParams()).getRules();
855 node = mGraph.mKeyNodes.get((rules[relation]));
856 if (node == null) return null;
866 private LayoutParams getRelatedViewParams(int[] rules, int relation) {
867 View v = getRelatedView(rules, relation);
869 ViewGroup.LayoutParams params = v.getLayoutParams();
870 if (params instanceof LayoutParams) {
871 return (LayoutParams) v.getLayoutParams();
877 private int getRelatedViewBaseline(int[] rules, int relation) {
878 View v = getRelatedView(rules, relation);
880 return v.getBaseline();
885 private void centerHorizontal(View child, LayoutParams params, int myWidth) {
886 int childWidth = child.getMeasuredWidth();
887 int left = (myWidth - childWidth) / 2;
890 params.mRight = left + childWidth;
893 private void centerVertical(View child, LayoutParams params, int myHeight) {
894 int childHeight = child.getMeasuredHeight();
895 int top = (myHeight - childHeight) / 2;
898 params.mBottom = top + childHeight;
902 protected void onLayout(boolean changed, int l, int t, int r, int b) {
903 // The layout has actually already been performed and the positions
904 // cached. Apply the cached values to the children.
905 int count = getChildCount();
907 for (int i = 0; i < count; i++) {
908 View child = getChildAt(i);
909 if (child.getVisibility() != GONE) {
910 RelativeLayout.LayoutParams st =
911 (RelativeLayout.LayoutParams) child.getLayoutParams();
912 child.layout(st.mLeft, st.mTop, st.mRight, st.mBottom);
919 public LayoutParams generateLayoutParams(AttributeSet attrs) {
920 return new RelativeLayout.LayoutParams(getContext(), attrs);
924 * Returns a set of layout parameters with a width of
925 * {@link android.view.ViewGroup.LayoutParams#WRAP_CONTENT},
926 * a height of {@link android.view.ViewGroup.LayoutParams#WRAP_CONTENT} and no spanning.
929 protected ViewGroup.LayoutParams generateDefaultLayoutParams() {
930 return new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
933 // Override to allow type-checking of LayoutParams.
935 protected boolean checkLayoutParams(ViewGroup.LayoutParams p) {
936 return p instanceof RelativeLayout.LayoutParams;
940 protected ViewGroup.LayoutParams generateLayoutParams(ViewGroup.LayoutParams p) {
941 return new LayoutParams(p);
945 public boolean dispatchPopulateAccessibilityEvent(AccessibilityEvent event) {
946 if (mTopToBottomLeftToRightSet == null) {
947 mTopToBottomLeftToRightSet = new TreeSet<View>(new TopToBottomLeftToRightComparator());
950 // sort children top-to-bottom and left-to-right
951 for (int i = 0, count = getChildCount(); i < count; i++) {
952 mTopToBottomLeftToRightSet.add(getChildAt(i));
955 for (View view : mTopToBottomLeftToRightSet) {
956 if (view.dispatchPopulateAccessibilityEvent(event)) {
957 mTopToBottomLeftToRightSet.clear();
962 mTopToBottomLeftToRightSet.clear();
967 * Compares two views in left-to-right and top-to-bottom fashion.
969 private class TopToBottomLeftToRightComparator implements Comparator<View> {
970 public int compare(View first, View second) {
972 int topDifference = first.getTop() - second.getTop();
973 if (topDifference != 0) {
974 return topDifference;
977 int leftDifference = first.getLeft() - second.getLeft();
978 if (leftDifference != 0) {
979 return leftDifference;
981 // break tie by height
982 int heightDiference = first.getHeight() - second.getHeight();
983 if (heightDiference != 0) {
984 return heightDiference;
986 // break tie by width
987 int widthDiference = first.getWidth() - second.getWidth();
988 if (widthDiference != 0) {
989 return widthDiference;
996 * Per-child layout information associated with RelativeLayout.
998 * @attr ref android.R.styleable#RelativeLayout_Layout_layout_alignWithParentIfMissing
999 * @attr ref android.R.styleable#RelativeLayout_Layout_layout_toLeftOf
1000 * @attr ref android.R.styleable#RelativeLayout_Layout_layout_toRightOf
1001 * @attr ref android.R.styleable#RelativeLayout_Layout_layout_above
1002 * @attr ref android.R.styleable#RelativeLayout_Layout_layout_below
1003 * @attr ref android.R.styleable#RelativeLayout_Layout_layout_alignBaseline
1004 * @attr ref android.R.styleable#RelativeLayout_Layout_layout_alignLeft
1005 * @attr ref android.R.styleable#RelativeLayout_Layout_layout_alignTop
1006 * @attr ref android.R.styleable#RelativeLayout_Layout_layout_alignRight
1007 * @attr ref android.R.styleable#RelativeLayout_Layout_layout_alignBottom
1008 * @attr ref android.R.styleable#RelativeLayout_Layout_layout_alignParentLeft
1009 * @attr ref android.R.styleable#RelativeLayout_Layout_layout_alignParentTop
1010 * @attr ref android.R.styleable#RelativeLayout_Layout_layout_alignParentRight
1011 * @attr ref android.R.styleable#RelativeLayout_Layout_layout_alignParentBottom
1012 * @attr ref android.R.styleable#RelativeLayout_Layout_layout_centerInParent
1013 * @attr ref android.R.styleable#RelativeLayout_Layout_layout_centerHorizontal
1014 * @attr ref android.R.styleable#RelativeLayout_Layout_layout_centerVertical
1016 public static class LayoutParams extends ViewGroup.MarginLayoutParams {
1017 @ViewDebug.ExportedProperty(category = "layout", resolveId = true, indexMapping = {
1018 @ViewDebug.IntToString(from = ABOVE, to = "above"),
1019 @ViewDebug.IntToString(from = ALIGN_BASELINE, to = "alignBaseline"),
1020 @ViewDebug.IntToString(from = ALIGN_BOTTOM, to = "alignBottom"),
1021 @ViewDebug.IntToString(from = ALIGN_LEFT, to = "alignLeft"),
1022 @ViewDebug.IntToString(from = ALIGN_PARENT_BOTTOM, to = "alignParentBottom"),
1023 @ViewDebug.IntToString(from = ALIGN_PARENT_LEFT, to = "alignParentLeft"),
1024 @ViewDebug.IntToString(from = ALIGN_PARENT_RIGHT, to = "alignParentRight"),
1025 @ViewDebug.IntToString(from = ALIGN_PARENT_TOP, to = "alignParentTop"),
1026 @ViewDebug.IntToString(from = ALIGN_RIGHT, to = "alignRight"),
1027 @ViewDebug.IntToString(from = ALIGN_TOP, to = "alignTop"),
1028 @ViewDebug.IntToString(from = BELOW, to = "below"),
1029 @ViewDebug.IntToString(from = CENTER_HORIZONTAL, to = "centerHorizontal"),
1030 @ViewDebug.IntToString(from = CENTER_IN_PARENT, to = "center"),
1031 @ViewDebug.IntToString(from = CENTER_VERTICAL, to = "centerVertical"),
1032 @ViewDebug.IntToString(from = LEFT_OF, to = "leftOf"),
1033 @ViewDebug.IntToString(from = RIGHT_OF, to = "rightOf")
1035 @ViewDebug.IntToString(from = TRUE, to = "true"),
1036 @ViewDebug.IntToString(from = 0, to = "false/NO_ID")
1038 private int[] mRules = new int[VERB_COUNT];
1040 private int mLeft, mTop, mRight, mBottom;
1043 * When true, uses the parent as the anchor if the anchor doesn't exist or if
1044 * the anchor's visibility is GONE.
1046 @ViewDebug.ExportedProperty(category = "layout")
1047 public boolean alignWithParent;
1049 public LayoutParams(Context c, AttributeSet attrs) {
1052 TypedArray a = c.obtainStyledAttributes(attrs,
1053 com.android.internal.R.styleable.RelativeLayout_Layout);
1055 final int[] rules = mRules;
1057 final int N = a.getIndexCount();
1058 for (int i = 0; i < N; i++) {
1059 int attr = a.getIndex(i);
1061 case com.android.internal.R.styleable.RelativeLayout_Layout_layout_alignWithParentIfMissing:
1062 alignWithParent = a.getBoolean(attr, false);
1064 case com.android.internal.R.styleable.RelativeLayout_Layout_layout_toLeftOf:
1065 rules[LEFT_OF] = a.getResourceId(attr, 0);
1067 case com.android.internal.R.styleable.RelativeLayout_Layout_layout_toRightOf:
1068 rules[RIGHT_OF] = a.getResourceId(attr, 0);
1070 case com.android.internal.R.styleable.RelativeLayout_Layout_layout_above:
1071 rules[ABOVE] = a.getResourceId(attr, 0);
1073 case com.android.internal.R.styleable.RelativeLayout_Layout_layout_below:
1074 rules[BELOW] = a.getResourceId(attr, 0);
1076 case com.android.internal.R.styleable.RelativeLayout_Layout_layout_alignBaseline:
1077 rules[ALIGN_BASELINE] = a.getResourceId(attr, 0);
1079 case com.android.internal.R.styleable.RelativeLayout_Layout_layout_alignLeft:
1080 rules[ALIGN_LEFT] = a.getResourceId(attr, 0);
1082 case com.android.internal.R.styleable.RelativeLayout_Layout_layout_alignTop:
1083 rules[ALIGN_TOP] = a.getResourceId(attr, 0);
1085 case com.android.internal.R.styleable.RelativeLayout_Layout_layout_alignRight:
1086 rules[ALIGN_RIGHT] = a.getResourceId(attr, 0);
1088 case com.android.internal.R.styleable.RelativeLayout_Layout_layout_alignBottom:
1089 rules[ALIGN_BOTTOM] = a.getResourceId(attr, 0);
1091 case com.android.internal.R.styleable.RelativeLayout_Layout_layout_alignParentLeft:
1092 rules[ALIGN_PARENT_LEFT] = a.getBoolean(attr, false) ? TRUE : 0;
1094 case com.android.internal.R.styleable.RelativeLayout_Layout_layout_alignParentTop:
1095 rules[ALIGN_PARENT_TOP] = a.getBoolean(attr, false) ? TRUE : 0;
1097 case com.android.internal.R.styleable.RelativeLayout_Layout_layout_alignParentRight:
1098 rules[ALIGN_PARENT_RIGHT] = a.getBoolean(attr, false) ? TRUE : 0;
1100 case com.android.internal.R.styleable.RelativeLayout_Layout_layout_alignParentBottom:
1101 rules[ALIGN_PARENT_BOTTOM] = a.getBoolean(attr, false) ? TRUE : 0;
1103 case com.android.internal.R.styleable.RelativeLayout_Layout_layout_centerInParent:
1104 rules[CENTER_IN_PARENT] = a.getBoolean(attr, false) ? TRUE : 0;
1106 case com.android.internal.R.styleable.RelativeLayout_Layout_layout_centerHorizontal:
1107 rules[CENTER_HORIZONTAL] = a.getBoolean(attr, false) ? TRUE : 0;
1109 case com.android.internal.R.styleable.RelativeLayout_Layout_layout_centerVertical:
1110 rules[CENTER_VERTICAL] = a.getBoolean(attr, false) ? TRUE : 0;
1118 public LayoutParams(int w, int h) {
1125 public LayoutParams(ViewGroup.LayoutParams source) {
1132 public LayoutParams(ViewGroup.MarginLayoutParams source) {
1137 public String debug(String output) {
1138 return output + "ViewGroup.LayoutParams={ width=" + sizeToString(width) +
1139 ", height=" + sizeToString(height) + " }";
1143 * Adds a layout rule to be interpreted by the RelativeLayout. This
1144 * method should only be used for constraints that don't refer to another sibling
1145 * (e.g., CENTER_IN_PARENT) or take a boolean value ({@link RelativeLayout#TRUE}
1146 * for true or - for false). To specify a verb that takes a subject, use
1147 * {@link #addRule(int, int)} instead.
1149 * @param verb One of the verbs defined by
1150 * {@link android.widget.RelativeLayout RelativeLayout}, such as
1151 * ALIGN_WITH_PARENT_LEFT.
1152 * @see #addRule(int, int)
1154 public void addRule(int verb) {
1155 mRules[verb] = TRUE;
1159 * Adds a layout rule to be interpreted by the RelativeLayout. Use this for
1160 * verbs that take a target, such as a sibling (ALIGN_RIGHT) or a boolean
1163 * @param verb One of the verbs defined by
1164 * {@link android.widget.RelativeLayout RelativeLayout}, such as
1165 * ALIGN_WITH_PARENT_LEFT.
1166 * @param anchor The id of another view to use as an anchor,
1167 * or a boolean value(represented as {@link RelativeLayout#TRUE})
1168 * for true or 0 for false). For verbs that don't refer to another sibling
1169 * (for example, ALIGN_WITH_PARENT_BOTTOM) just use -1.
1170 * @see #addRule(int)
1172 public void addRule(int verb, int anchor) {
1173 mRules[verb] = anchor;
1177 * Retrieves a complete list of all supported rules, where the index is the rule
1178 * verb, and the element value is the value specified, or "false" if it was never
1181 * @return the supported rules
1182 * @see #addRule(int, int)
1184 public int[] getRules() {
1189 private static class DependencyGraph {
1191 * List of all views in the graph.
1193 private ArrayList<Node> mNodes = new ArrayList<Node>();
1196 * List of nodes in the graph. Each node is identified by its
1197 * view id (see View#getId()).
1199 private SparseArray<Node> mKeyNodes = new SparseArray<Node>();
1202 * Temporary data structure used to build the list of roots
1205 private LinkedList<Node> mRoots = new LinkedList<Node>();
1211 final ArrayList<Node> nodes = mNodes;
1212 final int count = nodes.size();
1214 for (int i = 0; i < count; i++) {
1215 nodes.get(i).release();
1224 * Adds a view to the graph.
1226 * @param view The view to be added as a node to the graph.
1228 void add(View view) {
1229 final int id = view.getId();
1230 final Node node = Node.acquire(view);
1232 if (id != View.NO_ID) {
1233 mKeyNodes.put(id, node);
1240 * Builds a sorted list of views. The sorting order depends on the dependencies
1241 * between the view. For instance, if view C needs view A to be processed first
1242 * and view A needs view B to be processed first, the dependency graph
1243 * is: B -> A -> C. The sorted array will contain views B, A and C in this order.
1245 * @param sorted The sorted list of views. The length of this array must
1246 * be equal to getChildCount().
1247 * @param rules The list of rules to take into account.
1249 void getSortedViews(View[] sorted, int... rules) {
1250 final LinkedList<Node> roots = findRoots(rules);
1253 while (roots.size() > 0) {
1254 final Node node = roots.removeFirst();
1255 final View view = node.view;
1256 final int key = view.getId();
1258 sorted[index++] = view;
1260 final HashSet<Node> dependents = node.dependents;
1261 for (Node dependent : dependents) {
1262 final SparseArray<Node> dependencies = dependent.dependencies;
1264 dependencies.remove(key);
1265 if (dependencies.size() == 0) {
1266 roots.add(dependent);
1271 if (index < sorted.length) {
1272 throw new IllegalStateException("Circular dependencies cannot exist"
1273 + " in RelativeLayout");
1278 * Finds the roots of the graph. A root is a node with no dependency and
1279 * with [0..n] dependents.
1281 * @param rulesFilter The list of rules to consider when building the
1284 * @return A list of node, each being a root of the graph
1286 private LinkedList<Node> findRoots(int[] rulesFilter) {
1287 final SparseArray<Node> keyNodes = mKeyNodes;
1288 final ArrayList<Node> nodes = mNodes;
1289 final int count = nodes.size();
1291 // Find roots can be invoked several times, so make sure to clear
1292 // all dependents and dependencies before running the algorithm
1293 for (int i = 0; i < count; i++) {
1294 final Node node = nodes.get(i);
1295 node.dependents.clear();
1296 node.dependencies.clear();
1299 // Builds up the dependents and dependencies for each node of the graph
1300 for (int i = 0; i < count; i++) {
1301 final Node node = nodes.get(i);
1303 final LayoutParams layoutParams = (LayoutParams) node.view.getLayoutParams();
1304 final int[] rules = layoutParams.mRules;
1305 final int rulesCount = rulesFilter.length;
1307 // Look only the the rules passed in parameter, this way we build only the
1308 // dependencies for a specific set of rules
1309 for (int j = 0; j < rulesCount; j++) {
1310 final int rule = rules[rulesFilter[j]];
1312 // The node this node depends on
1313 final Node dependency = keyNodes.get(rule);
1314 // Skip unknowns and self dependencies
1315 if (dependency == null || dependency == node) {
1318 // Add the current node as a dependent
1319 dependency.dependents.add(node);
1320 // Add a dependency to the current node
1321 node.dependencies.put(rule, dependency);
1326 final LinkedList<Node> roots = mRoots;
1329 // Finds all the roots in the graph: all nodes with no dependencies
1330 for (int i = 0; i < count; i++) {
1331 final Node node = nodes.get(i);
1332 if (node.dependencies.size() == 0) roots.add(node);
1339 * Prints the dependency graph for the specified rules.
1341 * @param resources The context's resources to print the ids.
1342 * @param rules The list of rules to take into account.
1344 void log(Resources resources, int... rules) {
1345 final LinkedList<Node> roots = findRoots(rules);
1346 for (Node node : roots) {
1347 printNode(resources, node);
1351 static void printViewId(Resources resources, View view) {
1352 if (view.getId() != View.NO_ID) {
1353 d(LOG_TAG, resources.getResourceEntryName(view.getId()));
1355 d(LOG_TAG, "NO_ID");
1359 private static void appendViewId(Resources resources, Node node, StringBuilder buffer) {
1360 if (node.view.getId() != View.NO_ID) {
1361 buffer.append(resources.getResourceEntryName(node.view.getId()));
1363 buffer.append("NO_ID");
1367 private static void printNode(Resources resources, Node node) {
1368 if (node.dependents.size() == 0) {
1369 printViewId(resources, node.view);
1371 for (Node dependent : node.dependents) {
1372 StringBuilder buffer = new StringBuilder();
1373 appendViewId(resources, node, buffer);
1374 printdependents(resources, dependent, buffer);
1379 private static void printdependents(Resources resources, Node node, StringBuilder buffer) {
1380 buffer.append(" -> ");
1381 appendViewId(resources, node, buffer);
1383 if (node.dependents.size() == 0) {
1384 d(LOG_TAG, buffer.toString());
1386 for (Node dependent : node.dependents) {
1387 StringBuilder subBuffer = new StringBuilder(buffer);
1388 printdependents(resources, dependent, subBuffer);
1394 * A node in the dependency graph. A node is a view, its list of dependencies
1395 * and its list of dependents.
1397 * A node with no dependent is considered a root of the graph.
1399 static class Node implements Poolable<Node> {
1401 * The view representing this node in the layout.
1406 * The list of dependents for this node; a dependent is a node
1407 * that needs this node to be processed first.
1409 final HashSet<Node> dependents = new HashSet<Node>();
1412 * The list of dependencies for this node.
1414 final SparseArray<Node> dependencies = new SparseArray<Node>();
1417 * START POOL IMPLEMENTATION
1419 // The pool is static, so all nodes instances are shared across
1420 // activities, that's why we give it a rather high limit
1421 private static final int POOL_LIMIT = 100;
1422 private static final Pool<Node> sPool = Pools.synchronizedPool(
1423 Pools.finitePool(new PoolableManager<Node>() {
1424 public Node newInstance() {
1428 public void onAcquired(Node element) {
1431 public void onReleased(Node element) {
1438 public void setNextPoolable(Node element) {
1442 public Node getNextPoolable() {
1446 static Node acquire(View view) {
1447 final Node node = sPool.acquire();
1456 dependencies.clear();
1458 sPool.release(this);
1461 * END POOL IMPLEMENTATION