1/*
2 * Copyright (C) 2014 Google Inc.
3 * Licensed to The Android Open Source Project.
4 *
5 * Licensed under the Apache License, Version 2.0 (the "License");
6 * you may not use this file except in compliance with the License.
7 * You may obtain a copy of the License at
8 *
9 *      http://www.apache.org/licenses/LICENSE-2.0
10 *
11 * Unless required by applicable law or agreed to in writing, software
12 * distributed under the License is distributed on an "AS IS" BASIS,
13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 * See the License for the specific language governing permissions and
15 * limitations under the License.
16 */
17
18package com.android.mail.ui;
19
20import android.content.Context;
21import android.graphics.Rect;
22import android.util.AttributeSet;
23import android.widget.ListView;
24
25/**
26 * A list view that auto resizes depending on the height of the viewing frame. This means this
27 * list view will auto resize whenever the soft keyboard appears/disappears.
28 */
29public class AutoResizeListView extends ListView {
30    private final Rect mRect = new Rect();
31    private final int[] mCoords = new int[2];
32
33    public AutoResizeListView(Context context) {
34        this(context, null);
35    }
36
37    public AutoResizeListView(Context context, AttributeSet attrs) {
38        super(context, attrs);
39    }
40
41    @Override
42    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
43        getWindowVisibleDisplayFrame(mRect);
44        getLocationInWindow(mCoords);
45
46        // The desired height is the available height we have for VIEWING.
47        final int desiredHeight = mRect.bottom - mCoords[1];
48        final int heightMode = MeasureSpec.getMode(heightMeasureSpec);
49        final int heightSize = MeasureSpec.getSize(heightMeasureSpec);
50
51        // Measure height and obey the measure mode.
52        final int height;
53        if (heightMode == MeasureSpec.EXACTLY) {
54            height = heightSize;
55        } else {
56            // For AT_MOST and UNSPECIFIED we always want to get the minimum.
57            height = Math.min(desiredHeight, heightSize);
58        }
59
60        // Compile back to measure spec and pass it along
61        heightMeasureSpec = MeasureSpec.makeMeasureSpec(height, heightMode);
62
63        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
64    }
65}
66