RelativeLayout.java revision 946d05b95f849684b709a3750ef189388d6dc5a9
1/* 2 * Copyright (C) 2006 The Android Open Source Project 3 * 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 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 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. 15 */ 16 17package android.widget; 18 19import com.android.internal.R; 20 21import java.util.ArrayDeque; 22import java.util.ArrayList; 23import java.util.Comparator; 24import java.util.HashMap; 25import java.util.SortedSet; 26import java.util.TreeSet; 27 28import android.content.Context; 29import android.content.res.Resources; 30import android.content.res.TypedArray; 31import android.graphics.Rect; 32import android.util.AttributeSet; 33import android.util.Pool; 34import android.util.Poolable; 35import android.util.PoolableManager; 36import android.util.Pools; 37import android.util.SparseArray; 38import android.view.Gravity; 39import android.view.View; 40import android.view.ViewDebug; 41import android.view.ViewGroup; 42import android.view.accessibility.AccessibilityEvent; 43import android.view.accessibility.AccessibilityNodeInfo; 44import android.widget.RemoteViews.RemoteView; 45 46import static android.util.Log.d; 47 48/** 49 * A Layout where the positions of the children can be described in relation to each other or to the 50 * parent. 51 * 52 * <p> 53 * Note that you cannot have a circular dependency between the size of the RelativeLayout and the 54 * position of its children. For example, you cannot have a RelativeLayout whose height is set to 55 * {@link android.view.ViewGroup.LayoutParams#WRAP_CONTENT WRAP_CONTENT} and a child set to 56 * {@link #ALIGN_PARENT_BOTTOM}. 57 * </p> 58 * 59 * <p>See the <a href="{@docRoot}guide/topics/ui/layout/relative.html">Relative 60 * Layout</a> guide.</p> 61 * 62 * <p> 63 * Also see {@link android.widget.RelativeLayout.LayoutParams RelativeLayout.LayoutParams} for 64 * layout attributes 65 * </p> 66 * 67 * @attr ref android.R.styleable#RelativeLayout_gravity 68 * @attr ref android.R.styleable#RelativeLayout_ignoreGravity 69 */ 70@RemoteView 71public class RelativeLayout extends ViewGroup { 72 private static final String LOG_TAG = "RelativeLayout"; 73 74 private static final boolean DEBUG_GRAPH = false; 75 76 public static final int TRUE = -1; 77 78 /** 79 * Rule that aligns a child's right edge with another child's left edge. 80 */ 81 public static final int LEFT_OF = 0; 82 /** 83 * Rule that aligns a child's left edge with another child's right edge. 84 */ 85 public static final int RIGHT_OF = 1; 86 /** 87 * Rule that aligns a child's bottom edge with another child's top edge. 88 */ 89 public static final int ABOVE = 2; 90 /** 91 * Rule that aligns a child's top edge with another child's bottom edge. 92 */ 93 public static final int BELOW = 3; 94 95 /** 96 * Rule that aligns a child's baseline with another child's baseline. 97 */ 98 public static final int ALIGN_BASELINE = 4; 99 /** 100 * Rule that aligns a child's left edge with another child's left edge. 101 */ 102 public static final int ALIGN_LEFT = 5; 103 /** 104 * Rule that aligns a child's top edge with another child's top edge. 105 */ 106 public static final int ALIGN_TOP = 6; 107 /** 108 * Rule that aligns a child's right edge with another child's right edge. 109 */ 110 public static final int ALIGN_RIGHT = 7; 111 /** 112 * Rule that aligns a child's bottom edge with another child's bottom edge. 113 */ 114 public static final int ALIGN_BOTTOM = 8; 115 116 /** 117 * Rule that aligns the child's left edge with its RelativeLayout 118 * parent's left edge. 119 */ 120 public static final int ALIGN_PARENT_LEFT = 9; 121 /** 122 * Rule that aligns the child's top edge with its RelativeLayout 123 * parent's top edge. 124 */ 125 public static final int ALIGN_PARENT_TOP = 10; 126 /** 127 * Rule that aligns the child's right edge with its RelativeLayout 128 * parent's right edge. 129 */ 130 public static final int ALIGN_PARENT_RIGHT = 11; 131 /** 132 * Rule that aligns the child's bottom edge with its RelativeLayout 133 * parent's bottom edge. 134 */ 135 public static final int ALIGN_PARENT_BOTTOM = 12; 136 137 /** 138 * Rule that centers the child with respect to the bounds of its 139 * RelativeLayout parent. 140 */ 141 public static final int CENTER_IN_PARENT = 13; 142 /** 143 * Rule that centers the child horizontally with respect to the 144 * bounds of its RelativeLayout parent. 145 */ 146 public static final int CENTER_HORIZONTAL = 14; 147 /** 148 * Rule that centers the child vertically with respect to the 149 * bounds of its RelativeLayout parent. 150 */ 151 public static final int CENTER_VERTICAL = 15; 152 /** 153 * Rule that aligns a child's end edge with another child's start edge. 154 */ 155 public static final int START_OF = 16; 156 /** 157 * Rule that aligns a child's start edge with another child's end edge. 158 */ 159 public static final int END_OF = 17; 160 /** 161 * Rule that aligns a child's start edge with another child's start edge. 162 */ 163 public static final int ALIGN_START = 18; 164 /** 165 * Rule that aligns a child's end edge with another child's end edge. 166 */ 167 public static final int ALIGN_END = 19; 168 /** 169 * Rule that aligns the child's start edge with its RelativeLayout 170 * parent's start edge. 171 */ 172 public static final int ALIGN_PARENT_START = 20; 173 /** 174 * Rule that aligns the child's end edge with its RelativeLayout 175 * parent's end edge. 176 */ 177 public static final int ALIGN_PARENT_END = 21; 178 179 private static final int VERB_COUNT = 22; 180 181 182 private static final int[] RULES_VERTICAL = { 183 ABOVE, BELOW, ALIGN_BASELINE, ALIGN_TOP, ALIGN_BOTTOM 184 }; 185 186 private static final int[] RULES_HORIZONTAL = { 187 LEFT_OF, RIGHT_OF, ALIGN_LEFT, ALIGN_RIGHT, START_OF, END_OF, ALIGN_START, ALIGN_END 188 }; 189 190 private View mBaselineView = null; 191 private boolean mHasBaselineAlignedChild; 192 193 private int mGravity = Gravity.START | Gravity.TOP; 194 private final Rect mContentBounds = new Rect(); 195 private final Rect mSelfBounds = new Rect(); 196 private int mIgnoreGravity; 197 198 private SortedSet<View> mTopToBottomLeftToRightSet = null; 199 200 private boolean mDirtyHierarchy; 201 private View[] mSortedHorizontalChildren = new View[0]; 202 private View[] mSortedVerticalChildren = new View[0]; 203 private final DependencyGraph mGraph = new DependencyGraph(); 204 205 public RelativeLayout(Context context) { 206 super(context); 207 } 208 209 public RelativeLayout(Context context, AttributeSet attrs) { 210 super(context, attrs); 211 initFromAttributes(context, attrs); 212 } 213 214 public RelativeLayout(Context context, AttributeSet attrs, int defStyle) { 215 super(context, attrs, defStyle); 216 initFromAttributes(context, attrs); 217 } 218 219 private void initFromAttributes(Context context, AttributeSet attrs) { 220 TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.RelativeLayout); 221 mIgnoreGravity = a.getResourceId(R.styleable.RelativeLayout_ignoreGravity, View.NO_ID); 222 mGravity = a.getInt(R.styleable.RelativeLayout_gravity, mGravity); 223 a.recycle(); 224 } 225 226 @Override 227 public boolean shouldDelayChildPressedState() { 228 return false; 229 } 230 231 /** 232 * Defines which View is ignored when the gravity is applied. This setting has no 233 * effect if the gravity is <code>Gravity.START | Gravity.TOP</code>. 234 * 235 * @param viewId The id of the View to be ignored by gravity, or 0 if no View 236 * should be ignored. 237 * 238 * @see #setGravity(int) 239 * 240 * @attr ref android.R.styleable#RelativeLayout_ignoreGravity 241 */ 242 @android.view.RemotableViewMethod 243 public void setIgnoreGravity(int viewId) { 244 mIgnoreGravity = viewId; 245 } 246 247 /** 248 * Describes how the child views are positioned. 249 * 250 * @return the gravity. 251 * 252 * @see #setGravity(int) 253 * @see android.view.Gravity 254 * 255 * @attr ref android.R.styleable#RelativeLayout_gravity 256 */ 257 public int getGravity() { 258 return mGravity; 259 } 260 261 /** 262 * Describes how the child views are positioned. Defaults to 263 * <code>Gravity.START | Gravity.TOP</code>. 264 * 265 * <p>Note that since RelativeLayout considers the positioning of each child 266 * relative to one another to be significant, setting gravity will affect 267 * the positioning of all children as a single unit within the parent. 268 * This happens after children have been relatively positioned.</p> 269 * 270 * @param gravity See {@link android.view.Gravity} 271 * 272 * @see #setHorizontalGravity(int) 273 * @see #setVerticalGravity(int) 274 * 275 * @attr ref android.R.styleable#RelativeLayout_gravity 276 */ 277 @android.view.RemotableViewMethod 278 public void setGravity(int gravity) { 279 if (mGravity != gravity) { 280 if ((gravity & Gravity.RELATIVE_HORIZONTAL_GRAVITY_MASK) == 0) { 281 gravity |= Gravity.START; 282 } 283 284 if ((gravity & Gravity.VERTICAL_GRAVITY_MASK) == 0) { 285 gravity |= Gravity.TOP; 286 } 287 288 mGravity = gravity; 289 requestLayout(); 290 } 291 } 292 293 @android.view.RemotableViewMethod 294 public void setHorizontalGravity(int horizontalGravity) { 295 final int gravity = horizontalGravity & Gravity.RELATIVE_HORIZONTAL_GRAVITY_MASK; 296 if ((mGravity & Gravity.RELATIVE_HORIZONTAL_GRAVITY_MASK) != gravity) { 297 mGravity = (mGravity & ~Gravity.RELATIVE_HORIZONTAL_GRAVITY_MASK) | gravity; 298 requestLayout(); 299 } 300 } 301 302 @android.view.RemotableViewMethod 303 public void setVerticalGravity(int verticalGravity) { 304 final int gravity = verticalGravity & Gravity.VERTICAL_GRAVITY_MASK; 305 if ((mGravity & Gravity.VERTICAL_GRAVITY_MASK) != gravity) { 306 mGravity = (mGravity & ~Gravity.VERTICAL_GRAVITY_MASK) | gravity; 307 requestLayout(); 308 } 309 } 310 311 @Override 312 public int getBaseline() { 313 return mBaselineView != null ? mBaselineView.getBaseline() : super.getBaseline(); 314 } 315 316 @Override 317 public void requestLayout() { 318 super.requestLayout(); 319 mDirtyHierarchy = true; 320 } 321 322 private void sortChildren() { 323 int count = getChildCount(); 324 if (mSortedVerticalChildren.length != count) mSortedVerticalChildren = new View[count]; 325 if (mSortedHorizontalChildren.length != count) mSortedHorizontalChildren = new View[count]; 326 327 final DependencyGraph graph = mGraph; 328 graph.clear(); 329 330 for (int i = 0; i < count; i++) { 331 final View child = getChildAt(i); 332 graph.add(child); 333 } 334 335 if (DEBUG_GRAPH) { 336 d(LOG_TAG, "=== Sorted vertical children"); 337 graph.log(getResources(), RULES_VERTICAL); 338 d(LOG_TAG, "=== Sorted horizontal children"); 339 graph.log(getResources(), RULES_HORIZONTAL); 340 } 341 342 graph.getSortedViews(mSortedVerticalChildren, RULES_VERTICAL); 343 graph.getSortedViews(mSortedHorizontalChildren, RULES_HORIZONTAL); 344 345 if (DEBUG_GRAPH) { 346 d(LOG_TAG, "=== Ordered list of vertical children"); 347 for (View view : mSortedVerticalChildren) { 348 DependencyGraph.printViewId(getResources(), view); 349 } 350 d(LOG_TAG, "=== Ordered list of horizontal children"); 351 for (View view : mSortedHorizontalChildren) { 352 DependencyGraph.printViewId(getResources(), view); 353 } 354 } 355 } 356 357 // TODO: we need to find another way to implement RelativeLayout 358 // This implementation cannot handle every case 359 @Override 360 protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { 361 if (mDirtyHierarchy) { 362 mDirtyHierarchy = false; 363 sortChildren(); 364 } 365 366 int myWidth = -1; 367 int myHeight = -1; 368 369 int width = 0; 370 int height = 0; 371 372 int widthMode = MeasureSpec.getMode(widthMeasureSpec); 373 int heightMode = MeasureSpec.getMode(heightMeasureSpec); 374 int widthSize = MeasureSpec.getSize(widthMeasureSpec); 375 int heightSize = MeasureSpec.getSize(heightMeasureSpec); 376 377 // Record our dimensions if they are known; 378 if (widthMode != MeasureSpec.UNSPECIFIED) { 379 myWidth = widthSize; 380 } 381 382 if (heightMode != MeasureSpec.UNSPECIFIED) { 383 myHeight = heightSize; 384 } 385 386 if (widthMode == MeasureSpec.EXACTLY) { 387 width = myWidth; 388 } 389 390 if (heightMode == MeasureSpec.EXACTLY) { 391 height = myHeight; 392 } 393 394 mHasBaselineAlignedChild = false; 395 396 View ignore = null; 397 int gravity = mGravity & Gravity.RELATIVE_HORIZONTAL_GRAVITY_MASK; 398 final boolean horizontalGravity = gravity != Gravity.START && gravity != 0; 399 gravity = mGravity & Gravity.VERTICAL_GRAVITY_MASK; 400 final boolean verticalGravity = gravity != Gravity.TOP && gravity != 0; 401 402 int left = Integer.MAX_VALUE; 403 int top = Integer.MAX_VALUE; 404 int right = Integer.MIN_VALUE; 405 int bottom = Integer.MIN_VALUE; 406 407 boolean offsetHorizontalAxis = false; 408 boolean offsetVerticalAxis = false; 409 410 if ((horizontalGravity || verticalGravity) && mIgnoreGravity != View.NO_ID) { 411 ignore = findViewById(mIgnoreGravity); 412 } 413 414 final boolean isWrapContentWidth = widthMode != MeasureSpec.EXACTLY; 415 final boolean isWrapContentHeight = heightMode != MeasureSpec.EXACTLY; 416 417 View[] views = mSortedHorizontalChildren; 418 int count = views.length; 419 for (int i = 0; i < count; i++) { 420 View child = views[i]; 421 if (child.getVisibility() != GONE) { 422 LayoutParams params = (LayoutParams) child.getLayoutParams(); 423 424 applyHorizontalSizeRules(params, myWidth); 425 measureChildHorizontal(child, params, myWidth, myHeight); 426 if (positionChildHorizontal(child, params, myWidth, isWrapContentWidth)) { 427 offsetHorizontalAxis = true; 428 } 429 } 430 } 431 432 views = mSortedVerticalChildren; 433 count = views.length; 434 435 for (int i = 0; i < count; i++) { 436 View child = views[i]; 437 if (child.getVisibility() != GONE) { 438 LayoutParams params = (LayoutParams) child.getLayoutParams(); 439 440 applyVerticalSizeRules(params, myHeight); 441 measureChild(child, params, myWidth, myHeight); 442 if (positionChildVertical(child, params, myHeight, isWrapContentHeight)) { 443 offsetVerticalAxis = true; 444 } 445 446 if (isWrapContentWidth) { 447 width = Math.max(width, params.mRight); 448 } 449 450 if (isWrapContentHeight) { 451 height = Math.max(height, params.mBottom); 452 } 453 454 if (child != ignore || verticalGravity) { 455 left = Math.min(left, params.mLeft - params.leftMargin); 456 top = Math.min(top, params.mTop - params.topMargin); 457 } 458 459 if (child != ignore || horizontalGravity) { 460 right = Math.max(right, params.mRight + params.rightMargin); 461 bottom = Math.max(bottom, params.mBottom + params.bottomMargin); 462 } 463 } 464 } 465 466 if (mHasBaselineAlignedChild) { 467 for (int i = 0; i < count; i++) { 468 View child = getChildAt(i); 469 if (child.getVisibility() != GONE) { 470 LayoutParams params = (LayoutParams) child.getLayoutParams(); 471 alignBaseline(child, params); 472 473 if (child != ignore || verticalGravity) { 474 left = Math.min(left, params.mLeft - params.leftMargin); 475 top = Math.min(top, params.mTop - params.topMargin); 476 } 477 478 if (child != ignore || horizontalGravity) { 479 right = Math.max(right, params.mRight + params.rightMargin); 480 bottom = Math.max(bottom, params.mBottom + params.bottomMargin); 481 } 482 } 483 } 484 } 485 486 final int layoutDirection = getLayoutDirection(); 487 488 if (isWrapContentWidth) { 489 // Width already has left padding in it since it was calculated by looking at 490 // the right of each child view 491 width += mPaddingRight; 492 493 if (mLayoutParams.width >= 0) { 494 width = Math.max(width, mLayoutParams.width); 495 } 496 497 width = Math.max(width, getSuggestedMinimumWidth()); 498 width = resolveSize(width, widthMeasureSpec); 499 500 if (offsetHorizontalAxis) { 501 for (int i = 0; i < count; i++) { 502 View child = getChildAt(i); 503 if (child.getVisibility() != GONE) { 504 LayoutParams params = (LayoutParams) child.getLayoutParams(); 505 final int[] rules = params.getRules(layoutDirection); 506 if (rules[CENTER_IN_PARENT] != 0 || rules[CENTER_HORIZONTAL] != 0) { 507 centerHorizontal(child, params, width); 508 } else if (rules[ALIGN_PARENT_RIGHT] != 0) { 509 final int childWidth = child.getMeasuredWidth(); 510 params.mLeft = width - mPaddingRight - childWidth; 511 params.mRight = params.mLeft + childWidth; 512 } 513 } 514 } 515 } 516 } 517 518 if (isWrapContentHeight) { 519 // Height already has top padding in it since it was calculated by looking at 520 // the bottom of each child view 521 height += mPaddingBottom; 522 523 if (mLayoutParams.height >= 0) { 524 height = Math.max(height, mLayoutParams.height); 525 } 526 527 height = Math.max(height, getSuggestedMinimumHeight()); 528 height = resolveSize(height, heightMeasureSpec); 529 530 if (offsetVerticalAxis) { 531 for (int i = 0; i < count; i++) { 532 View child = getChildAt(i); 533 if (child.getVisibility() != GONE) { 534 LayoutParams params = (LayoutParams) child.getLayoutParams(); 535 final int[] rules = params.getRules(layoutDirection); 536 if (rules[CENTER_IN_PARENT] != 0 || rules[CENTER_VERTICAL] != 0) { 537 centerVertical(child, params, height); 538 } else if (rules[ALIGN_PARENT_BOTTOM] != 0) { 539 final int childHeight = child.getMeasuredHeight(); 540 params.mTop = height - mPaddingBottom - childHeight; 541 params.mBottom = params.mTop + childHeight; 542 } 543 } 544 } 545 } 546 } 547 548 if (horizontalGravity || verticalGravity) { 549 final Rect selfBounds = mSelfBounds; 550 selfBounds.set(mPaddingLeft, mPaddingTop, width - mPaddingRight, 551 height - mPaddingBottom); 552 553 final Rect contentBounds = mContentBounds; 554 Gravity.apply(mGravity, right - left, bottom - top, selfBounds, contentBounds, 555 layoutDirection); 556 557 final int horizontalOffset = contentBounds.left - left; 558 final int verticalOffset = contentBounds.top - top; 559 if (horizontalOffset != 0 || verticalOffset != 0) { 560 for (int i = 0; i < count; i++) { 561 View child = getChildAt(i); 562 if (child.getVisibility() != GONE && child != ignore) { 563 LayoutParams params = (LayoutParams) child.getLayoutParams(); 564 if (horizontalGravity) { 565 params.mLeft += horizontalOffset; 566 params.mRight += horizontalOffset; 567 } 568 if (verticalGravity) { 569 params.mTop += verticalOffset; 570 params.mBottom += verticalOffset; 571 } 572 } 573 } 574 } 575 } 576 577 setMeasuredDimension(width, height); 578 } 579 580 private void alignBaseline(View child, LayoutParams params) { 581 final int layoutDirection = getLayoutDirection(); 582 int[] rules = params.getRules(layoutDirection); 583 int anchorBaseline = getRelatedViewBaseline(rules, ALIGN_BASELINE); 584 585 if (anchorBaseline != -1) { 586 LayoutParams anchorParams = getRelatedViewParams(rules, ALIGN_BASELINE); 587 if (anchorParams != null) { 588 int offset = anchorParams.mTop + anchorBaseline; 589 int baseline = child.getBaseline(); 590 if (baseline != -1) { 591 offset -= baseline; 592 } 593 int height = params.mBottom - params.mTop; 594 params.mTop = offset; 595 params.mBottom = params.mTop + height; 596 } 597 } 598 599 if (mBaselineView == null) { 600 mBaselineView = child; 601 } else { 602 LayoutParams lp = (LayoutParams) mBaselineView.getLayoutParams(); 603 if (params.mTop < lp.mTop || (params.mTop == lp.mTop && params.mLeft < lp.mLeft)) { 604 mBaselineView = child; 605 } 606 } 607 } 608 609 /** 610 * Measure a child. The child should have left, top, right and bottom information 611 * stored in its LayoutParams. If any of these values is -1 it means that the view 612 * can extend up to the corresponding edge. 613 * 614 * @param child Child to measure 615 * @param params LayoutParams associated with child 616 * @param myWidth Width of the the RelativeLayout 617 * @param myHeight Height of the RelativeLayout 618 */ 619 private void measureChild(View child, LayoutParams params, int myWidth, int myHeight) { 620 int childWidthMeasureSpec = getChildMeasureSpec(params.mLeft, 621 params.mRight, params.width, 622 params.leftMargin, params.rightMargin, 623 mPaddingLeft, mPaddingRight, 624 myWidth); 625 int childHeightMeasureSpec = getChildMeasureSpec(params.mTop, 626 params.mBottom, params.height, 627 params.topMargin, params.bottomMargin, 628 mPaddingTop, mPaddingBottom, 629 myHeight); 630 child.measure(childWidthMeasureSpec, childHeightMeasureSpec); 631 } 632 633 private void measureChildHorizontal(View child, LayoutParams params, int myWidth, int myHeight) { 634 int childWidthMeasureSpec = getChildMeasureSpec(params.mLeft, 635 params.mRight, params.width, 636 params.leftMargin, params.rightMargin, 637 mPaddingLeft, mPaddingRight, 638 myWidth); 639 int childHeightMeasureSpec; 640 if (params.width == LayoutParams.MATCH_PARENT) { 641 childHeightMeasureSpec = MeasureSpec.makeMeasureSpec(myHeight, MeasureSpec.EXACTLY); 642 } else { 643 childHeightMeasureSpec = MeasureSpec.makeMeasureSpec(myHeight, MeasureSpec.AT_MOST); 644 } 645 child.measure(childWidthMeasureSpec, childHeightMeasureSpec); 646 } 647 648 /** 649 * Get a measure spec that accounts for all of the constraints on this view. 650 * This includes size constraints imposed by the RelativeLayout as well as 651 * the View's desired dimension. 652 * 653 * @param childStart The left or top field of the child's layout params 654 * @param childEnd The right or bottom field of the child's layout params 655 * @param childSize The child's desired size (the width or height field of 656 * the child's layout params) 657 * @param startMargin The left or top margin 658 * @param endMargin The right or bottom margin 659 * @param startPadding mPaddingLeft or mPaddingTop 660 * @param endPadding mPaddingRight or mPaddingBottom 661 * @param mySize The width or height of this view (the RelativeLayout) 662 * @return MeasureSpec for the child 663 */ 664 private int getChildMeasureSpec(int childStart, int childEnd, 665 int childSize, int startMargin, int endMargin, int startPadding, 666 int endPadding, int mySize) { 667 int childSpecMode = 0; 668 int childSpecSize = 0; 669 670 // Figure out start and end bounds. 671 int tempStart = childStart; 672 int tempEnd = childEnd; 673 674 // If the view did not express a layout constraint for an edge, use 675 // view's margins and our padding 676 if (tempStart < 0) { 677 tempStart = startPadding + startMargin; 678 } 679 if (tempEnd < 0) { 680 tempEnd = mySize - endPadding - endMargin; 681 } 682 683 // Figure out maximum size available to this view 684 int maxAvailable = tempEnd - tempStart; 685 686 if (childStart >= 0 && childEnd >= 0) { 687 // Constraints fixed both edges, so child must be an exact size 688 childSpecMode = MeasureSpec.EXACTLY; 689 childSpecSize = maxAvailable; 690 } else { 691 if (childSize >= 0) { 692 // Child wanted an exact size. Give as much as possible 693 childSpecMode = MeasureSpec.EXACTLY; 694 695 if (maxAvailable >= 0) { 696 // We have a maxmum size in this dimension. 697 childSpecSize = Math.min(maxAvailable, childSize); 698 } else { 699 // We can grow in this dimension. 700 childSpecSize = childSize; 701 } 702 } else if (childSize == LayoutParams.MATCH_PARENT) { 703 // Child wanted to be as big as possible. Give all available 704 // space 705 childSpecMode = MeasureSpec.EXACTLY; 706 childSpecSize = maxAvailable; 707 } else if (childSize == LayoutParams.WRAP_CONTENT) { 708 // Child wants to wrap content. Use AT_MOST 709 // to communicate available space if we know 710 // our max size 711 if (maxAvailable >= 0) { 712 // We have a maximum size in this dimension. 713 childSpecMode = MeasureSpec.AT_MOST; 714 childSpecSize = maxAvailable; 715 } else { 716 // We can grow in this dimension. Child can be as big as it 717 // wants 718 childSpecMode = MeasureSpec.UNSPECIFIED; 719 childSpecSize = 0; 720 } 721 } 722 } 723 724 return MeasureSpec.makeMeasureSpec(childSpecSize, childSpecMode); 725 } 726 727 private boolean positionChildHorizontal(View child, LayoutParams params, int myWidth, 728 boolean wrapContent) { 729 730 final int layoutDirection = getLayoutDirection(); 731 int[] rules = params.getRules(layoutDirection); 732 params.onResolveLayoutDirection(layoutDirection); 733 734 if (params.mLeft < 0 && params.mRight >= 0) { 735 // Right is fixed, but left varies 736 params.mLeft = params.mRight - child.getMeasuredWidth(); 737 } else if (params.mLeft >= 0 && params.mRight < 0) { 738 // Left is fixed, but right varies 739 params.mRight = params.mLeft + child.getMeasuredWidth(); 740 } else if (params.mLeft < 0 && params.mRight < 0) { 741 // Both left and right vary 742 if (rules[CENTER_IN_PARENT] != 0 || rules[CENTER_HORIZONTAL] != 0) { 743 if (!wrapContent) { 744 centerHorizontal(child, params, myWidth); 745 } else { 746 params.mLeft = mPaddingLeft + params.leftMargin; 747 params.mRight = params.mLeft + child.getMeasuredWidth(); 748 } 749 return true; 750 } else { 751 // This is the default case. For RTL we start from the right and for LTR we start 752 // from the left. This will give LEFT/TOP for LTR and RIGHT/TOP for RTL. 753 if (isLayoutRtl()) { 754 params.mRight = myWidth - mPaddingRight- params.rightMargin; 755 params.mLeft = params.mRight - child.getMeasuredWidth(); 756 } else { 757 params.mLeft = mPaddingLeft + params.leftMargin; 758 params.mRight = params.mLeft + child.getMeasuredWidth(); 759 } 760 } 761 } 762 return rules[ALIGN_PARENT_END] != 0; 763 } 764 765 private boolean positionChildVertical(View child, LayoutParams params, int myHeight, 766 boolean wrapContent) { 767 768 int[] rules = params.getRules(); 769 770 if (params.mTop < 0 && params.mBottom >= 0) { 771 // Bottom is fixed, but top varies 772 params.mTop = params.mBottom - child.getMeasuredHeight(); 773 } else if (params.mTop >= 0 && params.mBottom < 0) { 774 // Top is fixed, but bottom varies 775 params.mBottom = params.mTop + child.getMeasuredHeight(); 776 } else if (params.mTop < 0 && params.mBottom < 0) { 777 // Both top and bottom vary 778 if (rules[CENTER_IN_PARENT] != 0 || rules[CENTER_VERTICAL] != 0) { 779 if (!wrapContent) { 780 centerVertical(child, params, myHeight); 781 } else { 782 params.mTop = mPaddingTop + params.topMargin; 783 params.mBottom = params.mTop + child.getMeasuredHeight(); 784 } 785 return true; 786 } else { 787 params.mTop = mPaddingTop + params.topMargin; 788 params.mBottom = params.mTop + child.getMeasuredHeight(); 789 } 790 } 791 return rules[ALIGN_PARENT_BOTTOM] != 0; 792 } 793 794 private void applyHorizontalSizeRules(LayoutParams childParams, int myWidth) { 795 final int layoutDirection = getLayoutDirection(); 796 int[] rules = childParams.getRules(layoutDirection); 797 RelativeLayout.LayoutParams anchorParams; 798 799 // -1 indicated a "soft requirement" in that direction. For example: 800 // left=10, right=-1 means the view must start at 10, but can go as far as it wants to the right 801 // left =-1, right=10 means the view must end at 10, but can go as far as it wants to the left 802 // left=10, right=20 means the left and right ends are both fixed 803 childParams.mLeft = -1; 804 childParams.mRight = -1; 805 806 anchorParams = getRelatedViewParams(rules, LEFT_OF); 807 if (anchorParams != null) { 808 childParams.mRight = anchorParams.mLeft - (anchorParams.leftMargin + 809 childParams.rightMargin); 810 } else if (childParams.alignWithParent && rules[LEFT_OF] != 0) { 811 if (myWidth >= 0) { 812 childParams.mRight = myWidth - mPaddingRight - childParams.rightMargin; 813 } else { 814 // FIXME uh oh... 815 } 816 } 817 818 anchorParams = getRelatedViewParams(rules, RIGHT_OF); 819 if (anchorParams != null) { 820 childParams.mLeft = anchorParams.mRight + (anchorParams.rightMargin + 821 childParams.leftMargin); 822 } else if (childParams.alignWithParent && rules[RIGHT_OF] != 0) { 823 childParams.mLeft = mPaddingLeft + childParams.leftMargin; 824 } 825 826 anchorParams = getRelatedViewParams(rules, ALIGN_LEFT); 827 if (anchorParams != null) { 828 childParams.mLeft = anchorParams.mLeft + childParams.leftMargin; 829 } else if (childParams.alignWithParent && rules[ALIGN_LEFT] != 0) { 830 childParams.mLeft = mPaddingLeft + childParams.leftMargin; 831 } 832 833 anchorParams = getRelatedViewParams(rules, ALIGN_RIGHT); 834 if (anchorParams != null) { 835 childParams.mRight = anchorParams.mRight - childParams.rightMargin; 836 } else if (childParams.alignWithParent && rules[ALIGN_RIGHT] != 0) { 837 if (myWidth >= 0) { 838 childParams.mRight = myWidth - mPaddingRight - childParams.rightMargin; 839 } else { 840 // FIXME uh oh... 841 } 842 } 843 844 if (0 != rules[ALIGN_PARENT_LEFT]) { 845 childParams.mLeft = mPaddingLeft + childParams.leftMargin; 846 } 847 848 if (0 != rules[ALIGN_PARENT_RIGHT]) { 849 if (myWidth >= 0) { 850 childParams.mRight = myWidth - mPaddingRight - childParams.rightMargin; 851 } else { 852 // FIXME uh oh... 853 } 854 } 855 } 856 857 private void applyVerticalSizeRules(LayoutParams childParams, int myHeight) { 858 int[] rules = childParams.getRules(); 859 RelativeLayout.LayoutParams anchorParams; 860 861 childParams.mTop = -1; 862 childParams.mBottom = -1; 863 864 anchorParams = getRelatedViewParams(rules, ABOVE); 865 if (anchorParams != null) { 866 childParams.mBottom = anchorParams.mTop - (anchorParams.topMargin + 867 childParams.bottomMargin); 868 } else if (childParams.alignWithParent && rules[ABOVE] != 0) { 869 if (myHeight >= 0) { 870 childParams.mBottom = myHeight - mPaddingBottom - childParams.bottomMargin; 871 } else { 872 // FIXME uh oh... 873 } 874 } 875 876 anchorParams = getRelatedViewParams(rules, BELOW); 877 if (anchorParams != null) { 878 childParams.mTop = anchorParams.mBottom + (anchorParams.bottomMargin + 879 childParams.topMargin); 880 } else if (childParams.alignWithParent && rules[BELOW] != 0) { 881 childParams.mTop = mPaddingTop + childParams.topMargin; 882 } 883 884 anchorParams = getRelatedViewParams(rules, ALIGN_TOP); 885 if (anchorParams != null) { 886 childParams.mTop = anchorParams.mTop + childParams.topMargin; 887 } else if (childParams.alignWithParent && rules[ALIGN_TOP] != 0) { 888 childParams.mTop = mPaddingTop + childParams.topMargin; 889 } 890 891 anchorParams = getRelatedViewParams(rules, ALIGN_BOTTOM); 892 if (anchorParams != null) { 893 childParams.mBottom = anchorParams.mBottom - childParams.bottomMargin; 894 } else if (childParams.alignWithParent && rules[ALIGN_BOTTOM] != 0) { 895 if (myHeight >= 0) { 896 childParams.mBottom = myHeight - mPaddingBottom - childParams.bottomMargin; 897 } else { 898 // FIXME uh oh... 899 } 900 } 901 902 if (0 != rules[ALIGN_PARENT_TOP]) { 903 childParams.mTop = mPaddingTop + childParams.topMargin; 904 } 905 906 if (0 != rules[ALIGN_PARENT_BOTTOM]) { 907 if (myHeight >= 0) { 908 childParams.mBottom = myHeight - mPaddingBottom - childParams.bottomMargin; 909 } else { 910 // FIXME uh oh... 911 } 912 } 913 914 if (rules[ALIGN_BASELINE] != 0) { 915 mHasBaselineAlignedChild = true; 916 } 917 } 918 919 private View getRelatedView(int[] rules, int relation) { 920 int id = rules[relation]; 921 if (id != 0) { 922 DependencyGraph.Node node = mGraph.mKeyNodes.get(id); 923 if (node == null) return null; 924 View v = node.view; 925 926 // Find the first non-GONE view up the chain 927 while (v.getVisibility() == View.GONE) { 928 rules = ((LayoutParams) v.getLayoutParams()).getRules(); 929 node = mGraph.mKeyNodes.get((rules[relation])); 930 if (node == null) return null; 931 v = node.view; 932 } 933 934 return v; 935 } 936 937 return null; 938 } 939 940 private LayoutParams getRelatedViewParams(int[] rules, int relation) { 941 View v = getRelatedView(rules, relation); 942 if (v != null) { 943 ViewGroup.LayoutParams params = v.getLayoutParams(); 944 if (params instanceof LayoutParams) { 945 return (LayoutParams) v.getLayoutParams(); 946 } 947 } 948 return null; 949 } 950 951 private int getRelatedViewBaseline(int[] rules, int relation) { 952 View v = getRelatedView(rules, relation); 953 if (v != null) { 954 return v.getBaseline(); 955 } 956 return -1; 957 } 958 959 private void centerHorizontal(View child, LayoutParams params, int myWidth) { 960 int childWidth = child.getMeasuredWidth(); 961 int left = (myWidth - childWidth) / 2; 962 963 params.mLeft = left; 964 params.mRight = left + childWidth; 965 } 966 967 private void centerVertical(View child, LayoutParams params, int myHeight) { 968 int childHeight = child.getMeasuredHeight(); 969 int top = (myHeight - childHeight) / 2; 970 971 params.mTop = top; 972 params.mBottom = top + childHeight; 973 } 974 975 @Override 976 protected void onLayout(boolean changed, int l, int t, int r, int b) { 977 // The layout has actually already been performed and the positions 978 // cached. Apply the cached values to the children. 979 int count = getChildCount(); 980 981 for (int i = 0; i < count; i++) { 982 View child = getChildAt(i); 983 if (child.getVisibility() != GONE) { 984 RelativeLayout.LayoutParams st = 985 (RelativeLayout.LayoutParams) child.getLayoutParams(); 986 st.onResolveLayoutDirection(getLayoutDirection()); 987 child.layout(st.mLeft, st.mTop, st.mRight, st.mBottom); 988 } 989 } 990 } 991 992 @Override 993 public LayoutParams generateLayoutParams(AttributeSet attrs) { 994 return new RelativeLayout.LayoutParams(getContext(), attrs); 995 } 996 997 /** 998 * Returns a set of layout parameters with a width of 999 * {@link android.view.ViewGroup.LayoutParams#WRAP_CONTENT}, 1000 * a height of {@link android.view.ViewGroup.LayoutParams#WRAP_CONTENT} and no spanning. 1001 */ 1002 @Override 1003 protected ViewGroup.LayoutParams generateDefaultLayoutParams() { 1004 return new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT); 1005 } 1006 1007 // Override to allow type-checking of LayoutParams. 1008 @Override 1009 protected boolean checkLayoutParams(ViewGroup.LayoutParams p) { 1010 return p instanceof RelativeLayout.LayoutParams; 1011 } 1012 1013 @Override 1014 protected ViewGroup.LayoutParams generateLayoutParams(ViewGroup.LayoutParams p) { 1015 return new LayoutParams(p); 1016 } 1017 1018 @Override 1019 public boolean dispatchPopulateAccessibilityEvent(AccessibilityEvent event) { 1020 if (mTopToBottomLeftToRightSet == null) { 1021 mTopToBottomLeftToRightSet = new TreeSet<View>(new TopToBottomLeftToRightComparator()); 1022 } 1023 1024 // sort children top-to-bottom and left-to-right 1025 for (int i = 0, count = getChildCount(); i < count; i++) { 1026 mTopToBottomLeftToRightSet.add(getChildAt(i)); 1027 } 1028 1029 for (View view : mTopToBottomLeftToRightSet) { 1030 if (view.getVisibility() == View.VISIBLE 1031 && view.dispatchPopulateAccessibilityEvent(event)) { 1032 mTopToBottomLeftToRightSet.clear(); 1033 return true; 1034 } 1035 } 1036 1037 mTopToBottomLeftToRightSet.clear(); 1038 return false; 1039 } 1040 1041 @Override 1042 public void onInitializeAccessibilityEvent(AccessibilityEvent event) { 1043 super.onInitializeAccessibilityEvent(event); 1044 event.setClassName(RelativeLayout.class.getName()); 1045 } 1046 1047 @Override 1048 public void onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo info) { 1049 super.onInitializeAccessibilityNodeInfo(info); 1050 info.setClassName(RelativeLayout.class.getName()); 1051 } 1052 1053 /** 1054 * Compares two views in left-to-right and top-to-bottom fashion. 1055 */ 1056 private class TopToBottomLeftToRightComparator implements Comparator<View> { 1057 public int compare(View first, View second) { 1058 // top - bottom 1059 int topDifference = first.getTop() - second.getTop(); 1060 if (topDifference != 0) { 1061 return topDifference; 1062 } 1063 // left - right 1064 int leftDifference = first.getLeft() - second.getLeft(); 1065 if (leftDifference != 0) { 1066 return leftDifference; 1067 } 1068 // break tie by height 1069 int heightDiference = first.getHeight() - second.getHeight(); 1070 if (heightDiference != 0) { 1071 return heightDiference; 1072 } 1073 // break tie by width 1074 int widthDiference = first.getWidth() - second.getWidth(); 1075 if (widthDiference != 0) { 1076 return widthDiference; 1077 } 1078 return 0; 1079 } 1080 } 1081 1082 /** 1083 * Per-child layout information associated with RelativeLayout. 1084 * 1085 * @attr ref android.R.styleable#RelativeLayout_Layout_layout_alignWithParentIfMissing 1086 * @attr ref android.R.styleable#RelativeLayout_Layout_layout_toLeftOf 1087 * @attr ref android.R.styleable#RelativeLayout_Layout_layout_toRightOf 1088 * @attr ref android.R.styleable#RelativeLayout_Layout_layout_above 1089 * @attr ref android.R.styleable#RelativeLayout_Layout_layout_below 1090 * @attr ref android.R.styleable#RelativeLayout_Layout_layout_alignBaseline 1091 * @attr ref android.R.styleable#RelativeLayout_Layout_layout_alignLeft 1092 * @attr ref android.R.styleable#RelativeLayout_Layout_layout_alignTop 1093 * @attr ref android.R.styleable#RelativeLayout_Layout_layout_alignRight 1094 * @attr ref android.R.styleable#RelativeLayout_Layout_layout_alignBottom 1095 * @attr ref android.R.styleable#RelativeLayout_Layout_layout_alignParentLeft 1096 * @attr ref android.R.styleable#RelativeLayout_Layout_layout_alignParentTop 1097 * @attr ref android.R.styleable#RelativeLayout_Layout_layout_alignParentRight 1098 * @attr ref android.R.styleable#RelativeLayout_Layout_layout_alignParentBottom 1099 * @attr ref android.R.styleable#RelativeLayout_Layout_layout_centerInParent 1100 * @attr ref android.R.styleable#RelativeLayout_Layout_layout_centerHorizontal 1101 * @attr ref android.R.styleable#RelativeLayout_Layout_layout_centerVertical 1102 * @attr ref android.R.styleable#RelativeLayout_Layout_layout_toStartOf 1103 * @attr ref android.R.styleable#RelativeLayout_Layout_layout_toEndOf 1104 * @attr ref android.R.styleable#RelativeLayout_Layout_layout_alignStart 1105 * @attr ref android.R.styleable#RelativeLayout_Layout_layout_alignEnd 1106 * @attr ref android.R.styleable#RelativeLayout_Layout_layout_alignParentStart 1107 * @attr ref android.R.styleable#RelativeLayout_Layout_layout_alignParentEnd 1108 */ 1109 public static class LayoutParams extends ViewGroup.MarginLayoutParams { 1110 @ViewDebug.ExportedProperty(category = "layout", resolveId = true, indexMapping = { 1111 @ViewDebug.IntToString(from = ABOVE, to = "above"), 1112 @ViewDebug.IntToString(from = ALIGN_BASELINE, to = "alignBaseline"), 1113 @ViewDebug.IntToString(from = ALIGN_BOTTOM, to = "alignBottom"), 1114 @ViewDebug.IntToString(from = ALIGN_LEFT, to = "alignLeft"), 1115 @ViewDebug.IntToString(from = ALIGN_PARENT_BOTTOM, to = "alignParentBottom"), 1116 @ViewDebug.IntToString(from = ALIGN_PARENT_LEFT, to = "alignParentLeft"), 1117 @ViewDebug.IntToString(from = ALIGN_PARENT_RIGHT, to = "alignParentRight"), 1118 @ViewDebug.IntToString(from = ALIGN_PARENT_TOP, to = "alignParentTop"), 1119 @ViewDebug.IntToString(from = ALIGN_RIGHT, to = "alignRight"), 1120 @ViewDebug.IntToString(from = ALIGN_TOP, to = "alignTop"), 1121 @ViewDebug.IntToString(from = BELOW, to = "below"), 1122 @ViewDebug.IntToString(from = CENTER_HORIZONTAL, to = "centerHorizontal"), 1123 @ViewDebug.IntToString(from = CENTER_IN_PARENT, to = "center"), 1124 @ViewDebug.IntToString(from = CENTER_VERTICAL, to = "centerVertical"), 1125 @ViewDebug.IntToString(from = LEFT_OF, to = "leftOf"), 1126 @ViewDebug.IntToString(from = RIGHT_OF, to = "rightOf"), 1127 @ViewDebug.IntToString(from = ALIGN_START, to = "alignStart"), 1128 @ViewDebug.IntToString(from = ALIGN_END, to = "alignEnd"), 1129 @ViewDebug.IntToString(from = ALIGN_PARENT_START, to = "alignParentStart"), 1130 @ViewDebug.IntToString(from = ALIGN_PARENT_END, to = "alignParentEnd"), 1131 @ViewDebug.IntToString(from = START_OF, to = "startOf"), 1132 @ViewDebug.IntToString(from = END_OF, to = "endOf") 1133 }, mapping = { 1134 @ViewDebug.IntToString(from = TRUE, to = "true"), 1135 @ViewDebug.IntToString(from = 0, to = "false/NO_ID") 1136 }) 1137 1138 private int[] mRules = new int[VERB_COUNT]; 1139 private int[] mInitialRules = new int[VERB_COUNT]; 1140 1141 private int mLeft, mTop, mRight, mBottom; 1142 1143 private int mStart = DEFAULT_RELATIVE; 1144 private int mEnd = DEFAULT_RELATIVE; 1145 1146 private boolean mRulesChanged = false; 1147 1148 /** 1149 * When true, uses the parent as the anchor if the anchor doesn't exist or if 1150 * the anchor's visibility is GONE. 1151 */ 1152 @ViewDebug.ExportedProperty(category = "layout") 1153 public boolean alignWithParent; 1154 1155 public LayoutParams(Context c, AttributeSet attrs) { 1156 super(c, attrs); 1157 1158 TypedArray a = c.obtainStyledAttributes(attrs, 1159 com.android.internal.R.styleable.RelativeLayout_Layout); 1160 1161 final int[] rules = mRules; 1162 final int[] initialRules = mInitialRules; 1163 1164 final int N = a.getIndexCount(); 1165 for (int i = 0; i < N; i++) { 1166 int attr = a.getIndex(i); 1167 switch (attr) { 1168 case com.android.internal.R.styleable.RelativeLayout_Layout_layout_alignWithParentIfMissing: 1169 alignWithParent = a.getBoolean(attr, false); 1170 break; 1171 case com.android.internal.R.styleable.RelativeLayout_Layout_layout_toLeftOf: 1172 rules[LEFT_OF] = a.getResourceId(attr, 0); 1173 break; 1174 case com.android.internal.R.styleable.RelativeLayout_Layout_layout_toRightOf: 1175 rules[RIGHT_OF] = a.getResourceId(attr, 0); 1176 break; 1177 case com.android.internal.R.styleable.RelativeLayout_Layout_layout_above: 1178 rules[ABOVE] = a.getResourceId(attr, 0); 1179 break; 1180 case com.android.internal.R.styleable.RelativeLayout_Layout_layout_below: 1181 rules[BELOW] = a.getResourceId(attr, 0); 1182 break; 1183 case com.android.internal.R.styleable.RelativeLayout_Layout_layout_alignBaseline: 1184 rules[ALIGN_BASELINE] = a.getResourceId(attr, 0); 1185 break; 1186 case com.android.internal.R.styleable.RelativeLayout_Layout_layout_alignLeft: 1187 rules[ALIGN_LEFT] = a.getResourceId(attr, 0); 1188 break; 1189 case com.android.internal.R.styleable.RelativeLayout_Layout_layout_alignTop: 1190 rules[ALIGN_TOP] = a.getResourceId(attr, 0); 1191 break; 1192 case com.android.internal.R.styleable.RelativeLayout_Layout_layout_alignRight: 1193 rules[ALIGN_RIGHT] = a.getResourceId(attr, 0); 1194 break; 1195 case com.android.internal.R.styleable.RelativeLayout_Layout_layout_alignBottom: 1196 rules[ALIGN_BOTTOM] = a.getResourceId(attr, 0); 1197 break; 1198 case com.android.internal.R.styleable.RelativeLayout_Layout_layout_alignParentLeft: 1199 rules[ALIGN_PARENT_LEFT] = a.getBoolean(attr, false) ? TRUE : 0; 1200 break; 1201 case com.android.internal.R.styleable.RelativeLayout_Layout_layout_alignParentTop: 1202 rules[ALIGN_PARENT_TOP] = a.getBoolean(attr, false) ? TRUE : 0; 1203 break; 1204 case com.android.internal.R.styleable.RelativeLayout_Layout_layout_alignParentRight: 1205 rules[ALIGN_PARENT_RIGHT] = a.getBoolean(attr, false) ? TRUE : 0; 1206 break; 1207 case com.android.internal.R.styleable.RelativeLayout_Layout_layout_alignParentBottom: 1208 rules[ALIGN_PARENT_BOTTOM] = a.getBoolean(attr, false) ? TRUE : 0; 1209 break; 1210 case com.android.internal.R.styleable.RelativeLayout_Layout_layout_centerInParent: 1211 rules[CENTER_IN_PARENT] = a.getBoolean(attr, false) ? TRUE : 0; 1212 break; 1213 case com.android.internal.R.styleable.RelativeLayout_Layout_layout_centerHorizontal: 1214 rules[CENTER_HORIZONTAL] = a.getBoolean(attr, false) ? TRUE : 0; 1215 break; 1216 case com.android.internal.R.styleable.RelativeLayout_Layout_layout_centerVertical: 1217 rules[CENTER_VERTICAL] = a.getBoolean(attr, false) ? TRUE : 0; 1218 break; 1219 case com.android.internal.R.styleable.RelativeLayout_Layout_layout_toStartOf: 1220 rules[START_OF] = a.getResourceId(attr, 0); 1221 break; 1222 case com.android.internal.R.styleable.RelativeLayout_Layout_layout_toEndOf: 1223 rules[END_OF] = a.getResourceId(attr, 0); 1224 break; 1225 case com.android.internal.R.styleable.RelativeLayout_Layout_layout_alignStart: 1226 rules[ALIGN_START] = a.getResourceId(attr, 0); 1227 break; 1228 case com.android.internal.R.styleable.RelativeLayout_Layout_layout_alignEnd: 1229 rules[ALIGN_END] = a.getResourceId(attr, 0); 1230 break; 1231 case com.android.internal.R.styleable.RelativeLayout_Layout_layout_alignParentStart: 1232 rules[ALIGN_PARENT_START] = a.getBoolean(attr, false) ? TRUE : 0; 1233 break; 1234 case com.android.internal.R.styleable.RelativeLayout_Layout_layout_alignParentEnd: 1235 rules[ALIGN_PARENT_END] = a.getBoolean(attr, false) ? TRUE : 0; 1236 break; 1237 } 1238 } 1239 1240 for (int n = LEFT_OF; n < VERB_COUNT; n++) { 1241 initialRules[n] = rules[n]; 1242 } 1243 1244 a.recycle(); 1245 } 1246 1247 public LayoutParams(int w, int h) { 1248 super(w, h); 1249 } 1250 1251 /** 1252 * {@inheritDoc} 1253 */ 1254 public LayoutParams(ViewGroup.LayoutParams source) { 1255 super(source); 1256 } 1257 1258 /** 1259 * {@inheritDoc} 1260 */ 1261 public LayoutParams(ViewGroup.MarginLayoutParams source) { 1262 super(source); 1263 } 1264 1265 @Override 1266 public String debug(String output) { 1267 return output + "ViewGroup.LayoutParams={ width=" + sizeToString(width) + 1268 ", height=" + sizeToString(height) + " }"; 1269 } 1270 1271 /** 1272 * Adds a layout rule to be interpreted by the RelativeLayout. This 1273 * method should only be used for constraints that don't refer to another sibling 1274 * (e.g., CENTER_IN_PARENT) or take a boolean value ({@link RelativeLayout#TRUE} 1275 * for true or 0 for false). To specify a verb that takes a subject, use 1276 * {@link #addRule(int, int)} instead. 1277 * 1278 * @param verb One of the verbs defined by 1279 * {@link android.widget.RelativeLayout RelativeLayout}, such as 1280 * ALIGN_WITH_PARENT_LEFT. 1281 * @see #addRule(int, int) 1282 */ 1283 public void addRule(int verb) { 1284 mRules[verb] = TRUE; 1285 mInitialRules[verb] = TRUE; 1286 mRulesChanged = true; 1287 } 1288 1289 /** 1290 * Adds a layout rule to be interpreted by the RelativeLayout. Use this for 1291 * verbs that take a target, such as a sibling (ALIGN_RIGHT) or a boolean 1292 * value (VISIBLE). 1293 * 1294 * @param verb One of the verbs defined by 1295 * {@link android.widget.RelativeLayout RelativeLayout}, such as 1296 * ALIGN_WITH_PARENT_LEFT. 1297 * @param anchor The id of another view to use as an anchor, 1298 * or a boolean value(represented as {@link RelativeLayout#TRUE}) 1299 * for true or 0 for false). For verbs that don't refer to another sibling 1300 * (for example, ALIGN_WITH_PARENT_BOTTOM) just use -1. 1301 * @see #addRule(int) 1302 */ 1303 public void addRule(int verb, int anchor) { 1304 mRules[verb] = anchor; 1305 mInitialRules[verb] = anchor; 1306 mRulesChanged = true; 1307 } 1308 1309 /** 1310 * Removes a layout rule to be interpreted by the RelativeLayout. 1311 * 1312 * @param verb One of the verbs defined by 1313 * {@link android.widget.RelativeLayout RelativeLayout}, such as 1314 * ALIGN_WITH_PARENT_LEFT. 1315 * @see #addRule(int) 1316 * @see #addRule(int, int) 1317 */ 1318 public void removeRule(int verb) { 1319 mRules[verb] = 0; 1320 mInitialRules[verb] = 0; 1321 mRulesChanged = true; 1322 } 1323 1324 private boolean hasRelativeRules() { 1325 return (mInitialRules[START_OF] != 0 || mInitialRules[END_OF] != 0 || 1326 mInitialRules[ALIGN_START] != 0 || mInitialRules[ALIGN_END] != 0 || 1327 mInitialRules[ALIGN_PARENT_START] != 0 || mInitialRules[ALIGN_PARENT_END] != 0); 1328 } 1329 1330 private void resolveRules(int layoutDirection) { 1331 final boolean isLayoutRtl = (layoutDirection == View.LAYOUT_DIRECTION_RTL); 1332 // Reset to initial state 1333 for (int n = LEFT_OF; n < VERB_COUNT; n++) { 1334 mRules[n] = mInitialRules[n]; 1335 } 1336 // Apply rules depending on direction 1337 if (mRules[ALIGN_START] != 0) { 1338 mRules[isLayoutRtl ? ALIGN_RIGHT : ALIGN_LEFT] = mRules[ALIGN_START]; 1339 } 1340 if (mRules[ALIGN_END] != 0) { 1341 mRules[isLayoutRtl ? ALIGN_LEFT : ALIGN_RIGHT] = mRules[ALIGN_END]; 1342 } 1343 if (mRules[START_OF] != 0) { 1344 mRules[isLayoutRtl ? RIGHT_OF : LEFT_OF] = mRules[START_OF]; 1345 } 1346 if (mRules[END_OF] != 0) { 1347 mRules[isLayoutRtl ? LEFT_OF : RIGHT_OF] = mRules[END_OF]; 1348 } 1349 if (mRules[ALIGN_PARENT_START] != 0) { 1350 mRules[isLayoutRtl ? ALIGN_PARENT_RIGHT : ALIGN_PARENT_LEFT] = mRules[ALIGN_PARENT_START]; 1351 } 1352 if (mRules[ALIGN_PARENT_END] != 0) { 1353 mRules[isLayoutRtl ? ALIGN_PARENT_LEFT : ALIGN_PARENT_RIGHT] = mRules[ALIGN_PARENT_END]; 1354 } 1355 mRulesChanged = false; 1356 } 1357 1358 /** 1359 * Retrieves a complete list of all supported rules, where the index is the rule 1360 * verb, and the element value is the value specified, or "false" if it was never 1361 * set. If there are relative rules defined (*_START / *_END), they will be resolved 1362 * depending on the layout direction. 1363 * 1364 * @param layoutDirection the direction of the layout. 1365 * Should be either {@link View#LAYOUT_DIRECTION_LTR} 1366 * or {@link View#LAYOUT_DIRECTION_RTL} 1367 * @return the supported rules 1368 * @see #addRule(int, int) 1369 * 1370 * @hide 1371 */ 1372 public int[] getRules(int layoutDirection) { 1373 if (hasRelativeRules() && 1374 (mRulesChanged || layoutDirection != getLayoutDirection())) { 1375 resolveRules(layoutDirection); 1376 if (layoutDirection != getLayoutDirection()) { 1377 setLayoutDirection(layoutDirection); 1378 } 1379 } 1380 return mRules; 1381 } 1382 1383 /** 1384 * Retrieves a complete list of all supported rules, where the index is the rule 1385 * verb, and the element value is the value specified, or "false" if it was never 1386 * set. There will be no resolution of relative rules done. 1387 * 1388 * @return the supported rules 1389 * @see #addRule(int, int) 1390 */ 1391 public int[] getRules() { 1392 return mRules; 1393 } 1394 1395 @Override 1396 public void onResolveLayoutDirection(int layoutDirection) { 1397 final boolean isLayoutRtl = isLayoutRtl(); 1398 if (isLayoutRtl) { 1399 if (mStart != DEFAULT_RELATIVE) mRight = mStart; 1400 if (mEnd != DEFAULT_RELATIVE) mLeft = mEnd; 1401 } else { 1402 if (mStart != DEFAULT_RELATIVE) mLeft = mStart; 1403 if (mEnd != DEFAULT_RELATIVE) mRight = mEnd; 1404 } 1405 1406 if (hasRelativeRules() && layoutDirection != getLayoutDirection()) { 1407 resolveRules(layoutDirection); 1408 } 1409 // This will set the layout direction 1410 super.onResolveLayoutDirection(layoutDirection); 1411 } 1412 } 1413 1414 private static class DependencyGraph { 1415 /** 1416 * List of all views in the graph. 1417 */ 1418 private ArrayList<Node> mNodes = new ArrayList<Node>(); 1419 1420 /** 1421 * List of nodes in the graph. Each node is identified by its 1422 * view id (see View#getId()). 1423 */ 1424 private SparseArray<Node> mKeyNodes = new SparseArray<Node>(); 1425 1426 /** 1427 * Temporary data structure used to build the list of roots 1428 * for this graph. 1429 */ 1430 private ArrayDeque<Node> mRoots = new ArrayDeque<Node>(); 1431 1432 /** 1433 * Clears the graph. 1434 */ 1435 void clear() { 1436 final ArrayList<Node> nodes = mNodes; 1437 final int count = nodes.size(); 1438 1439 for (int i = 0; i < count; i++) { 1440 nodes.get(i).release(); 1441 } 1442 nodes.clear(); 1443 1444 mKeyNodes.clear(); 1445 mRoots.clear(); 1446 } 1447 1448 /** 1449 * Adds a view to the graph. 1450 * 1451 * @param view The view to be added as a node to the graph. 1452 */ 1453 void add(View view) { 1454 final int id = view.getId(); 1455 final Node node = Node.acquire(view); 1456 1457 if (id != View.NO_ID) { 1458 mKeyNodes.put(id, node); 1459 } 1460 1461 mNodes.add(node); 1462 } 1463 1464 /** 1465 * Builds a sorted list of views. The sorting order depends on the dependencies 1466 * between the view. For instance, if view C needs view A to be processed first 1467 * and view A needs view B to be processed first, the dependency graph 1468 * is: B -> A -> C. The sorted array will contain views B, A and C in this order. 1469 * 1470 * @param sorted The sorted list of views. The length of this array must 1471 * be equal to getChildCount(). 1472 * @param rules The list of rules to take into account. 1473 */ 1474 void getSortedViews(View[] sorted, int... rules) { 1475 final ArrayDeque<Node> roots = findRoots(rules); 1476 int index = 0; 1477 1478 Node node; 1479 while ((node = roots.pollLast()) != null) { 1480 final View view = node.view; 1481 final int key = view.getId(); 1482 1483 sorted[index++] = view; 1484 1485 final HashMap<Node, DependencyGraph> dependents = node.dependents; 1486 for (Node dependent : dependents.keySet()) { 1487 final SparseArray<Node> dependencies = dependent.dependencies; 1488 1489 dependencies.remove(key); 1490 if (dependencies.size() == 0) { 1491 roots.add(dependent); 1492 } 1493 } 1494 } 1495 1496 if (index < sorted.length) { 1497 throw new IllegalStateException("Circular dependencies cannot exist" 1498 + " in RelativeLayout"); 1499 } 1500 } 1501 1502 /** 1503 * Finds the roots of the graph. A root is a node with no dependency and 1504 * with [0..n] dependents. 1505 * 1506 * @param rulesFilter The list of rules to consider when building the 1507 * dependencies 1508 * 1509 * @return A list of node, each being a root of the graph 1510 */ 1511 private ArrayDeque<Node> findRoots(int[] rulesFilter) { 1512 final SparseArray<Node> keyNodes = mKeyNodes; 1513 final ArrayList<Node> nodes = mNodes; 1514 final int count = nodes.size(); 1515 1516 // Find roots can be invoked several times, so make sure to clear 1517 // all dependents and dependencies before running the algorithm 1518 for (int i = 0; i < count; i++) { 1519 final Node node = nodes.get(i); 1520 node.dependents.clear(); 1521 node.dependencies.clear(); 1522 } 1523 1524 // Builds up the dependents and dependencies for each node of the graph 1525 for (int i = 0; i < count; i++) { 1526 final Node node = nodes.get(i); 1527 1528 final LayoutParams layoutParams = (LayoutParams) node.view.getLayoutParams(); 1529 final int[] rules = layoutParams.mRules; 1530 final int rulesCount = rulesFilter.length; 1531 1532 // Look only the the rules passed in parameter, this way we build only the 1533 // dependencies for a specific set of rules 1534 for (int j = 0; j < rulesCount; j++) { 1535 final int rule = rules[rulesFilter[j]]; 1536 if (rule > 0) { 1537 // The node this node depends on 1538 final Node dependency = keyNodes.get(rule); 1539 // Skip unknowns and self dependencies 1540 if (dependency == null || dependency == node) { 1541 continue; 1542 } 1543 // Add the current node as a dependent 1544 dependency.dependents.put(node, this); 1545 // Add a dependency to the current node 1546 node.dependencies.put(rule, dependency); 1547 } 1548 } 1549 } 1550 1551 final ArrayDeque<Node> roots = mRoots; 1552 roots.clear(); 1553 1554 // Finds all the roots in the graph: all nodes with no dependencies 1555 for (int i = 0; i < count; i++) { 1556 final Node node = nodes.get(i); 1557 if (node.dependencies.size() == 0) roots.addLast(node); 1558 } 1559 1560 return roots; 1561 } 1562 1563 /** 1564 * Prints the dependency graph for the specified rules. 1565 * 1566 * @param resources The context's resources to print the ids. 1567 * @param rules The list of rules to take into account. 1568 */ 1569 void log(Resources resources, int... rules) { 1570 final ArrayDeque<Node> roots = findRoots(rules); 1571 for (Node node : roots) { 1572 printNode(resources, node); 1573 } 1574 } 1575 1576 static void printViewId(Resources resources, View view) { 1577 if (view.getId() != View.NO_ID) { 1578 d(LOG_TAG, resources.getResourceEntryName(view.getId())); 1579 } else { 1580 d(LOG_TAG, "NO_ID"); 1581 } 1582 } 1583 1584 private static void appendViewId(Resources resources, Node node, StringBuilder buffer) { 1585 if (node.view.getId() != View.NO_ID) { 1586 buffer.append(resources.getResourceEntryName(node.view.getId())); 1587 } else { 1588 buffer.append("NO_ID"); 1589 } 1590 } 1591 1592 private static void printNode(Resources resources, Node node) { 1593 if (node.dependents.size() == 0) { 1594 printViewId(resources, node.view); 1595 } else { 1596 for (Node dependent : node.dependents.keySet()) { 1597 StringBuilder buffer = new StringBuilder(); 1598 appendViewId(resources, node, buffer); 1599 printdependents(resources, dependent, buffer); 1600 } 1601 } 1602 } 1603 1604 private static void printdependents(Resources resources, Node node, StringBuilder buffer) { 1605 buffer.append(" -> "); 1606 appendViewId(resources, node, buffer); 1607 1608 if (node.dependents.size() == 0) { 1609 d(LOG_TAG, buffer.toString()); 1610 } else { 1611 for (Node dependent : node.dependents.keySet()) { 1612 StringBuilder subBuffer = new StringBuilder(buffer); 1613 printdependents(resources, dependent, subBuffer); 1614 } 1615 } 1616 } 1617 1618 /** 1619 * A node in the dependency graph. A node is a view, its list of dependencies 1620 * and its list of dependents. 1621 * 1622 * A node with no dependent is considered a root of the graph. 1623 */ 1624 static class Node implements Poolable<Node> { 1625 /** 1626 * The view representing this node in the layout. 1627 */ 1628 View view; 1629 1630 /** 1631 * The list of dependents for this node; a dependent is a node 1632 * that needs this node to be processed first. 1633 */ 1634 final HashMap<Node, DependencyGraph> dependents = new HashMap<Node, DependencyGraph>(); 1635 1636 /** 1637 * The list of dependencies for this node. 1638 */ 1639 final SparseArray<Node> dependencies = new SparseArray<Node>(); 1640 1641 /* 1642 * START POOL IMPLEMENTATION 1643 */ 1644 // The pool is static, so all nodes instances are shared across 1645 // activities, that's why we give it a rather high limit 1646 private static final int POOL_LIMIT = 100; 1647 private static final Pool<Node> sPool = Pools.synchronizedPool( 1648 Pools.finitePool(new PoolableManager<Node>() { 1649 public Node newInstance() { 1650 return new Node(); 1651 } 1652 1653 public void onAcquired(Node element) { 1654 } 1655 1656 public void onReleased(Node element) { 1657 } 1658 }, POOL_LIMIT) 1659 ); 1660 1661 private Node mNext; 1662 private boolean mIsPooled; 1663 1664 public void setNextPoolable(Node element) { 1665 mNext = element; 1666 } 1667 1668 public Node getNextPoolable() { 1669 return mNext; 1670 } 1671 1672 public boolean isPooled() { 1673 return mIsPooled; 1674 } 1675 1676 public void setPooled(boolean isPooled) { 1677 mIsPooled = isPooled; 1678 } 1679 1680 static Node acquire(View view) { 1681 final Node node = sPool.acquire(); 1682 node.view = view; 1683 1684 return node; 1685 } 1686 1687 void release() { 1688 view = null; 1689 dependents.clear(); 1690 dependencies.clear(); 1691 1692 sPool.release(this); 1693 } 1694 /* 1695 * END POOL IMPLEMENTATION 1696 */ 1697 } 1698 } 1699} 1700