AppsCustomizeTabHost.java revision 8b805b17158886035b38261eb611d8641701ae43
1/*
2 * Copyright (C) 2011 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 com.android.launcher2;
18
19import android.animation.Animator;
20import android.animation.AnimatorListenerAdapter;
21import android.animation.AnimatorSet;
22import android.animation.ObjectAnimator;
23import android.content.Context;
24import android.content.res.Resources;
25import android.util.AttributeSet;
26import android.view.LayoutInflater;
27import android.view.MotionEvent;
28import android.view.View;
29import android.view.ViewGroup;
30import android.widget.FrameLayout;
31import android.widget.LinearLayout;
32import android.widget.TabHost;
33import android.widget.TabWidget;
34import android.widget.TextView;
35
36import com.android.launcher.R;
37
38import java.util.ArrayList;
39
40public class AppsCustomizeTabHost extends TabHost implements LauncherTransitionable,
41        TabHost.OnTabChangeListener  {
42    static final String LOG_TAG = "AppsCustomizeTabHost";
43
44    private static final String APPS_TAB_TAG = "APPS";
45    private static final String WIDGETS_TAB_TAG = "WIDGETS";
46
47    private final LayoutInflater mLayoutInflater;
48    private ViewGroup mTabs;
49    private ViewGroup mTabsContainer;
50    private AppsCustomizePagedView mAppsCustomizePane;
51    private boolean mSuppressContentCallback = false;
52    private FrameLayout mAnimationBuffer;
53    private LinearLayout mContent;
54
55    private boolean mInTransition;
56    private boolean mTransitioningToWorkspace;
57    private boolean mResetAfterTransition;
58    private Runnable mRelayoutAndMakeVisible;
59
60    private Launcher mLauncher;
61
62    public AppsCustomizeTabHost(Context context, AttributeSet attrs) {
63        super(context, attrs);
64        mLayoutInflater = LayoutInflater.from(context);
65        mRelayoutAndMakeVisible = new Runnable() {
66                public void run() {
67                    mTabs.requestLayout();
68                    mTabsContainer.setAlpha(1f);
69                }
70            };
71    }
72
73    public void setup(Launcher launcher) {
74        mLauncher = launcher;
75    }
76
77    /**
78     * Convenience methods to select specific tabs.  We want to set the content type immediately
79     * in these cases, but we note that we still call setCurrentTabByTag() so that the tab view
80     * reflects the new content (but doesn't do the animation and logic associated with changing
81     * tabs manually).
82     */
83    private void setContentTypeImmediate(AppsCustomizePagedView.ContentType type) {
84        onTabChangedStart();
85        onTabChangedEnd(type);
86    }
87    void selectAppsTab() {
88        setContentTypeImmediate(AppsCustomizePagedView.ContentType.Applications);
89        setCurrentTabByTag(APPS_TAB_TAG);
90    }
91    void selectWidgetsTab() {
92        setContentTypeImmediate(AppsCustomizePagedView.ContentType.Widgets);
93        setCurrentTabByTag(WIDGETS_TAB_TAG);
94    }
95
96    /**
97     * Setup the tab host and create all necessary tabs.
98     */
99    @Override
100    protected void onFinishInflate() {
101        // Setup the tab host
102        setup();
103
104        final ViewGroup tabsContainer = (ViewGroup) findViewById(R.id.tabs_container);
105        final TabWidget tabs = getTabWidget();
106        final AppsCustomizePagedView appsCustomizePane = (AppsCustomizePagedView)
107                findViewById(R.id.apps_customize_pane_content);
108        mTabs = tabs;
109        mTabsContainer = tabsContainer;
110        mAppsCustomizePane = appsCustomizePane;
111        mAnimationBuffer = (FrameLayout) findViewById(R.id.animation_buffer);
112        mContent = (LinearLayout) findViewById(R.id.apps_customize_content);
113        if (tabs == null || mAppsCustomizePane == null) throw new Resources.NotFoundException();
114
115        // Configure the tabs content factory to return the same paged view (that we change the
116        // content filter on)
117        TabContentFactory contentFactory = new TabContentFactory() {
118            public View createTabContent(String tag) {
119                return appsCustomizePane;
120            }
121        };
122
123        // Create the tabs
124        TextView tabView;
125        String label;
126        label = getContext().getString(R.string.all_apps_button_label);
127        tabView = (TextView) mLayoutInflater.inflate(R.layout.tab_widget_indicator, tabs, false);
128        tabView.setText(label);
129        tabView.setContentDescription(label);
130        addTab(newTabSpec(APPS_TAB_TAG).setIndicator(tabView).setContent(contentFactory));
131        label = getContext().getString(R.string.widgets_tab_label);
132        tabView = (TextView) mLayoutInflater.inflate(R.layout.tab_widget_indicator, tabs, false);
133        tabView.setText(label);
134        tabView.setContentDescription(label);
135        addTab(newTabSpec(WIDGETS_TAB_TAG).setIndicator(tabView).setContent(contentFactory));
136        setOnTabChangedListener(this);
137
138        // Setup the key listener to jump between the last tab view and the market icon
139        AppsCustomizeTabKeyEventListener keyListener = new AppsCustomizeTabKeyEventListener();
140        View lastTab = tabs.getChildTabViewAt(tabs.getTabCount() - 1);
141        lastTab.setOnKeyListener(keyListener);
142        View shopButton = findViewById(R.id.market_button);
143        shopButton.setOnKeyListener(keyListener);
144
145        // Hide the tab bar until we measure
146        mTabsContainer.setAlpha(0f);
147    }
148
149    @Override
150    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
151        boolean remeasureTabWidth = (mTabs.getLayoutParams().width <= 0);
152        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
153
154        // Set the width of the tab list to the content width
155        if (remeasureTabWidth) {
156            int contentWidth = mAppsCustomizePane.getPageContentWidth();
157            if (contentWidth > 0 && mTabs.getLayoutParams().width != contentWidth) {
158                // Set the width and show the tab bar
159                mTabs.getLayoutParams().width = contentWidth;
160                post(mRelayoutAndMakeVisible);
161            }
162        }
163        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
164    }
165
166     public boolean onInterceptTouchEvent(MotionEvent ev) {
167         // If we are mid transition then intercept touch events here so we can ignore them
168         if (mInTransition) {
169             return true;
170         }
171         return super.onInterceptTouchEvent(ev);
172     };
173
174    @Override
175    public boolean onTouchEvent(MotionEvent event) {
176        // Allow touch events to fall through if we are transitioning to the workspace
177        if (mInTransition) {
178            if (mTransitioningToWorkspace) {
179                return super.onTouchEvent(event);
180            }
181        }
182
183        // Intercept all touch events up to the bottom of the AppsCustomizePane so they do not fall
184        // through to the workspace and trigger showWorkspace()
185        if (event.getY() < mAppsCustomizePane.getBottom()) {
186            return true;
187        }
188        return super.onTouchEvent(event);
189    }
190
191    private void onTabChangedStart() {
192        mAppsCustomizePane.hideScrollingIndicator(false);
193    }
194
195    private void reloadCurrentPage() {
196        if (!LauncherApplication.isScreenLarge()) {
197            mAppsCustomizePane.flashScrollingIndicator(true);
198        }
199        mAppsCustomizePane.loadAssociatedPages(mAppsCustomizePane.getCurrentPage());
200        mAppsCustomizePane.requestFocus();
201    }
202
203    private void onTabChangedEnd(AppsCustomizePagedView.ContentType type) {
204        mAppsCustomizePane.setContentType(type);
205    }
206
207    @Override
208    public void onTabChanged(String tabId) {
209        final AppsCustomizePagedView.ContentType type = getContentTypeForTabTag(tabId);
210        if (mSuppressContentCallback) {
211            mSuppressContentCallback = false;
212            return;
213        }
214
215        // Animate the changing of the tab content by fading pages in and out
216        final Resources res = getResources();
217        final int duration = res.getInteger(R.integer.config_tabTransitionDuration);
218
219        // We post a runnable here because there is a delay while the first page is loading and
220        // the feedback from having changed the tab almost feels better than having it stick
221        post(new Runnable() {
222            @Override
223            public void run() {
224                if (mAppsCustomizePane.getMeasuredWidth() <= 0 ||
225                        mAppsCustomizePane.getMeasuredHeight() <= 0) {
226                    reloadCurrentPage();
227                    return;
228                }
229
230                // Take the visible pages and re-parent them temporarily to mAnimatorBuffer
231                // and then cross fade to the new pages
232                int[] visiblePageRange = new int[2];
233                mAppsCustomizePane.getVisiblePages(visiblePageRange);
234                if (visiblePageRange[0] == -1 && visiblePageRange[1] == -1) {
235                    // If we can't get the visible page ranges, then just skip the animation
236                    reloadCurrentPage();
237                    return;
238                }
239                ArrayList<View> visiblePages = new ArrayList<View>();
240                for (int i = visiblePageRange[0]; i <= visiblePageRange[1]; i++) {
241                    visiblePages.add(mAppsCustomizePane.getPageAt(i));
242                }
243
244                // We want the pages to be rendered in exactly the same way as they were when
245                // their parent was mAppsCustomizePane -- so set the scroll on mAnimationBuffer
246                // to be exactly the same as mAppsCustomizePane, and below, set the left/top
247                // parameters to be correct for each of the pages
248                mAnimationBuffer.scrollTo(mAppsCustomizePane.getScrollX(), 0);
249
250                // mAppsCustomizePane renders its children in reverse order, so
251                // add the pages to mAnimationBuffer in reverse order to match that behavior
252                for (int i = visiblePages.size() - 1; i >= 0; i--) {
253                    View child = visiblePages.get(i);
254                    if (child instanceof PagedViewCellLayout) {
255                        ((PagedViewCellLayout) child).resetChildrenOnKeyListeners();
256                    } else if (child instanceof PagedViewGridLayout) {
257                        ((PagedViewGridLayout) child).resetChildrenOnKeyListeners();
258                    }
259                    PagedViewWidget.setDeletePreviewsWhenDetachedFromWindow(false);
260                    mAppsCustomizePane.removeView(child);
261                    PagedViewWidget.setDeletePreviewsWhenDetachedFromWindow(true);
262                    mAnimationBuffer.setAlpha(1f);
263                    mAnimationBuffer.setVisibility(View.VISIBLE);
264                    LayoutParams p = new FrameLayout.LayoutParams(child.getMeasuredWidth(),
265                            child.getMeasuredHeight());
266                    p.setMargins((int) child.getLeft(), (int) child.getTop(), 0, 0);
267                    mAnimationBuffer.addView(child, p);
268                }
269
270                // Toggle the new content
271                onTabChangedStart();
272                onTabChangedEnd(type);
273
274                // Animate the transition
275                ObjectAnimator outAnim = ObjectAnimator.ofFloat(mAnimationBuffer, "alpha", 0f);
276                outAnim.addListener(new AnimatorListenerAdapter() {
277                    @Override
278                    public void onAnimationEnd(Animator animation) {
279                        mAnimationBuffer.setVisibility(View.GONE);
280                        mAnimationBuffer.removeAllViews();
281                    }
282                    @Override
283                    public void onAnimationCancel(Animator animation) {
284                        mAnimationBuffer.setVisibility(View.GONE);
285                        mAnimationBuffer.removeAllViews();
286                    }
287                });
288                ObjectAnimator inAnim = ObjectAnimator.ofFloat(mAppsCustomizePane, "alpha", 1f);
289                inAnim.addListener(new AnimatorListenerAdapter() {
290                    @Override
291                    public void onAnimationEnd(Animator animation) {
292                        reloadCurrentPage();
293                    }
294                });
295                AnimatorSet animSet = new AnimatorSet();
296                animSet.playTogether(outAnim, inAnim);
297                animSet.setDuration(duration);
298                animSet.start();
299            }
300        });
301    }
302
303    public void setCurrentTabFromContent(AppsCustomizePagedView.ContentType type) {
304        mSuppressContentCallback = true;
305        setCurrentTabByTag(getTabTagForContentType(type));
306    }
307
308    /**
309     * Returns the content type for the specified tab tag.
310     */
311    public AppsCustomizePagedView.ContentType getContentTypeForTabTag(String tag) {
312        if (tag.equals(APPS_TAB_TAG)) {
313            return AppsCustomizePagedView.ContentType.Applications;
314        } else if (tag.equals(WIDGETS_TAB_TAG)) {
315            return AppsCustomizePagedView.ContentType.Widgets;
316        }
317        return AppsCustomizePagedView.ContentType.Applications;
318    }
319
320    /**
321     * Returns the tab tag for a given content type.
322     */
323    public String getTabTagForContentType(AppsCustomizePagedView.ContentType type) {
324        if (type == AppsCustomizePagedView.ContentType.Applications) {
325            return APPS_TAB_TAG;
326        } else if (type == AppsCustomizePagedView.ContentType.Widgets) {
327            return WIDGETS_TAB_TAG;
328        }
329        return APPS_TAB_TAG;
330    }
331
332    /**
333     * Disable focus on anything under this view in the hierarchy if we are not visible.
334     */
335    @Override
336    public int getDescendantFocusability() {
337        if (getVisibility() != View.VISIBLE) {
338            return ViewGroup.FOCUS_BLOCK_DESCENDANTS;
339        }
340        return super.getDescendantFocusability();
341    }
342
343    void reset() {
344        if (mInTransition) {
345            // Defer to after the transition to reset
346            mResetAfterTransition = true;
347        } else {
348            // Reset immediately
349            mAppsCustomizePane.reset();
350        }
351    }
352
353    private void enableAndBuildHardwareLayer() {
354        // isHardwareAccelerated() checks if we're attached to a window and if that
355        // window is HW accelerated-- we were sometimes not attached to a window
356        // and buildLayer was throwing an IllegalStateException
357        if (isHardwareAccelerated()) {
358            // Turn on hardware layers for performance
359            setLayerType(LAYER_TYPE_HARDWARE, null);
360
361            // force building the layer, so you don't get a blip early in an animation
362            // when the layer is created layer
363            buildLayer();
364
365            // Let the GC system know that now is a good time to do any garbage
366            // collection; makes it less likely we'll get a GC during the all apps
367            // to workspace animation
368            System.gc();
369        }
370    }
371
372    @Override
373    public View getContent() {
374        return mContent;
375    }
376
377    /* LauncherTransitionable overrides */
378    @Override
379    public void onLauncherTransitionStart(Launcher l, boolean animated, boolean toWorkspace) {
380        mAppsCustomizePane.onLauncherTransitionStart(l, animated, toWorkspace);
381        mInTransition = true;
382        mTransitioningToWorkspace = toWorkspace;
383
384        if (toWorkspace) {
385            // Going from All Apps -> Workspace
386            setVisibilityOfSiblingsWithLowerZOrder(VISIBLE);
387            // Stop the scrolling indicator - we don't want All Apps to be invalidating itself
388            // during the transition, especially since it has a hardware layer set on it
389            mAppsCustomizePane.cancelScrollingIndicatorAnimations();
390        } else {
391            // Going from Workspace -> All Apps
392            mContent.setVisibility(VISIBLE);
393
394            // Make sure the current page is loaded (we start loading the side pages after the
395            // transition to prevent slowing down the animation)
396            mAppsCustomizePane.loadAssociatedPages(mAppsCustomizePane.getCurrentPage(), true);
397
398            if (!LauncherApplication.isScreenLarge()) {
399                mAppsCustomizePane.showScrollingIndicator(true);
400            }
401        }
402
403        if (mResetAfterTransition) {
404            mAppsCustomizePane.reset();
405            mResetAfterTransition = false;
406        }
407
408        if (animated) {
409            enableAndBuildHardwareLayer();
410        }
411    }
412
413    @Override
414    public void onLauncherTransitionStep(Launcher l, float t) {
415        // Do nothing
416    }
417
418    @Override
419    public void onLauncherTransitionEnd(Launcher l, boolean animated, boolean toWorkspace) {
420        mAppsCustomizePane.onLauncherTransitionEnd(l, animated, toWorkspace);
421        mInTransition = false;
422        if (animated) {
423            setLayerType(LAYER_TYPE_NONE, null);
424        }
425
426        if (!toWorkspace) {
427            // Going from Workspace -> All Apps
428            setVisibilityOfSiblingsWithLowerZOrder(INVISIBLE);
429
430            // Dismiss the workspace cling and show the all apps cling (if not already shown)
431            l.dismissWorkspaceCling(null);
432            mAppsCustomizePane.showAllAppsCling();
433            // Make sure adjacent pages are loaded (we wait until after the transition to
434            // prevent slowing down the animation)
435            mAppsCustomizePane.loadAssociatedPages(mAppsCustomizePane.getCurrentPage());
436
437            if (!LauncherApplication.isScreenLarge()) {
438                mAppsCustomizePane.hideScrollingIndicator(false);
439            }
440        }
441    }
442
443    private void setVisibilityOfSiblingsWithLowerZOrder(int visibility) {
444        ViewGroup parent = (ViewGroup) getParent();
445        if (parent == null) return;
446
447        final int count = parent.getChildCount();
448        if (!isChildrenDrawingOrderEnabled()) {
449            for (int i = 0; i < count; i++) {
450                final View child = parent.getChildAt(i);
451                if (child == this) {
452                    break;
453                } else {
454                    if (child.getVisibility() == GONE) {
455                        continue;
456                    }
457                    child.setVisibility(visibility);
458                }
459            }
460        } else {
461            throw new RuntimeException("Failed; can't get z-order of views");
462        }
463    }
464
465    public void onWindowVisible() {
466        if (getVisibility() == VISIBLE) {
467            mContent.setVisibility(VISIBLE);
468            // We unload the widget previews when the UI is hidden, so need to reload pages
469            // Load the current page synchronously, and the neighboring pages asynchronously
470            mAppsCustomizePane.loadAssociatedPages(mAppsCustomizePane.getCurrentPage(), true);
471            mAppsCustomizePane.loadAssociatedPages(mAppsCustomizePane.getCurrentPage());
472
473            // We had to enable the wallpaper visibility when launching apps from all apps (so that
474            // the transitions would be the same as when launching from workspace) so we need to
475            // re-disable the wallpaper visibility to ensure performance.
476            int duration = getResources().getInteger(android.R.integer.config_shortAnimTime);
477            postDelayed(new Runnable() {
478                @Override
479                public void run() {
480                    mLauncher.updateWallpaperVisibility(false);
481                }
482            }, duration);
483        }
484    }
485
486    public void onTrimMemory() {
487        mContent.setVisibility(GONE);
488        // Clear the widget pages of all their subviews - this will trigger the widget previews
489        // to delete their bitmaps
490        mAppsCustomizePane.clearAllWidgetPages();
491    }
492
493    boolean isTransitioning() {
494        return mInTransition;
495    }
496}
497