2 * Copyright (C) 2008 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 com.android.contacts;
19 import android.content.Context;
20 import android.util.AttributeSet;
21 import android.view.View;
22 import android.view.ViewGroup;
23 import android.view.View.MeasureSpec;
25 public class ButtonGridLayout extends ViewGroup {
27 private final int mColumns = 3;
29 public ButtonGridLayout(Context context) {
33 public ButtonGridLayout(Context context, AttributeSet attrs) {
34 super(context, attrs);
37 public ButtonGridLayout(Context context, AttributeSet attrs, int defStyle) {
38 super(context, attrs, defStyle);
42 protected void onLayout(boolean changed, int l, int t, int r, int b) {
44 final int rows = getRows();
45 final View child0 = getChildAt(0);
46 final int yInc = (getHeight() - mPaddingTop - mPaddingBottom) / rows;
47 final int xInc = (getWidth() - mPaddingLeft - mPaddingRight) / mColumns;
48 final int childWidth = child0.getMeasuredWidth();
49 final int childHeight = child0.getMeasuredHeight();
50 final int xOffset = (xInc - childWidth) / 2;
51 final int yOffset = (yInc - childHeight) / 2;
53 for (int row = 0; row < rows; row++) {
55 for (int col = 0; col < mColumns; col++) {
56 int cell = row * mColumns + col;
57 if (cell >= getChildCount()) {
60 View child = getChildAt(cell);
61 child.layout(x + xOffset, y + yOffset,
62 x + xOffset + childWidth,
63 y + yOffset + childHeight);
70 private int getRows() {
71 return (getChildCount() + mColumns - 1) / mColumns;
75 protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
76 int width = mPaddingLeft + mPaddingRight;
77 int height = mPaddingTop + mPaddingBottom;
79 // Measure the first child and get it's size
80 View child = getChildAt(0);
81 child.measure(MeasureSpec.UNSPECIFIED , MeasureSpec.UNSPECIFIED);
82 int childWidth = child.getMeasuredWidth();
83 int childHeight = child.getMeasuredHeight();
84 // Make sure the other children are measured as well, to initialize
85 for (int i = 1; i < getChildCount(); i++) {
86 getChildAt(0).measure(MeasureSpec.UNSPECIFIED , MeasureSpec.UNSPECIFIED);
88 // All cells are going to be the size of the first child
89 width += mColumns * childWidth;
90 height += getRows() * childHeight;
92 width = resolveSize(width, widthMeasureSpec);
93 height = resolveSize(height, heightMeasureSpec);
94 setMeasuredDimension(width, height);