1/*
2 * Copyright (C) 2014 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 */
16package com.android.contacts.common.list;
17
18import android.content.Context;
19import android.content.res.ColorStateList;
20import android.content.res.TypedArray;
21import android.graphics.Outline;
22import android.support.v4.view.PagerAdapter;
23import android.support.v4.view.ViewPager;
24import android.util.AttributeSet;
25import android.util.TypedValue;
26import android.view.Gravity;
27import android.view.LayoutInflater;
28import android.view.View;
29import android.view.ViewOutlineProvider;
30import android.widget.FrameLayout;
31import android.widget.HorizontalScrollView;
32import android.widget.LinearLayout;
33import android.widget.TextView;
34import android.widget.Toast;
35
36import com.android.contacts.common.R;
37import com.android.contacts.common.compat.CompatUtils;
38
39/**
40 * Lightweight implementation of ViewPager tabs. This looks similar to traditional actionBar tabs,
41 * but allows for the view containing the tabs to be placed anywhere on screen. Text-related
42 * attributes can also be assigned in XML - these will get propogated to the child TextViews
43 * automatically.
44 */
45public class ViewPagerTabs extends HorizontalScrollView implements ViewPager.OnPageChangeListener {
46
47    ViewPager mPager;
48    private ViewPagerTabStrip mTabStrip;
49
50    /**
51     * Linearlayout that will contain the TextViews serving as tabs. This is the only child
52     * of the parent HorizontalScrollView.
53     */
54    final int mTextStyle;
55    final ColorStateList mTextColor;
56    final int mTextSize;
57    final boolean mTextAllCaps;
58    int mPrevSelected = -1;
59    int mSidePadding;
60
61    private int[] mTabIcons;
62    // For displaying the unread count next to the tab icon.
63    private int[] mUnreadCounts;
64
65    private static final ViewOutlineProvider VIEW_BOUNDS_OUTLINE_PROVIDER;
66    static {
67        if (CompatUtils.isLollipopCompatible()) {
68            VIEW_BOUNDS_OUTLINE_PROVIDER = new ViewOutlineProvider() {
69                @Override
70                public void getOutline(View view, Outline outline) {
71                    outline.setRect(0, 0, view.getWidth(), view.getHeight());
72                }
73            };
74        } else {
75            VIEW_BOUNDS_OUTLINE_PROVIDER = null;
76        }
77    }
78
79    private static final int TAB_SIDE_PADDING_IN_DPS = 10;
80
81    // TODO: This should use <declare-styleable> in the future
82    private static final int[] ATTRS = new int[] {
83        android.R.attr.textSize,
84        android.R.attr.textStyle,
85        android.R.attr.textColor,
86        android.R.attr.textAllCaps
87    };
88
89    /**
90     * Simulates actionbar tab behavior by showing a toast with the tab title when long clicked.
91     */
92    private class OnTabLongClickListener implements OnLongClickListener {
93        final int mPosition;
94
95        public OnTabLongClickListener(int position) {
96            mPosition = position;
97        }
98
99        @Override
100        public boolean onLongClick(View v) {
101            final int[] screenPos = new int[2];
102            getLocationOnScreen(screenPos);
103
104            final Context context = getContext();
105            final int width = getWidth();
106            final int height = getHeight();
107            final int screenWidth = context.getResources().getDisplayMetrics().widthPixels;
108
109            Toast toast = Toast.makeText(context, mPager.getAdapter().getPageTitle(mPosition),
110                    Toast.LENGTH_SHORT);
111
112            // Show the toast under the tab
113            toast.setGravity(Gravity.TOP | Gravity.CENTER_HORIZONTAL,
114                    (screenPos[0] + width / 2) - screenWidth / 2, screenPos[1] + height);
115
116            toast.show();
117            return true;
118        }
119    }
120
121    public ViewPagerTabs(Context context) {
122        this(context, null);
123    }
124
125    public ViewPagerTabs(Context context, AttributeSet attrs) {
126        this(context, attrs, 0);
127    }
128
129    public ViewPagerTabs(Context context, AttributeSet attrs, int defStyle) {
130        super(context, attrs, defStyle);
131        setFillViewport(true);
132
133        mSidePadding = (int) (getResources().getDisplayMetrics().density * TAB_SIDE_PADDING_IN_DPS);
134
135        final TypedArray a = context.obtainStyledAttributes(attrs, ATTRS);
136        mTextSize = a.getDimensionPixelSize(0, 0);
137        mTextStyle = a.getInt(1, 0);
138        mTextColor = a.getColorStateList(2);
139        mTextAllCaps = a.getBoolean(3, false);
140
141        mTabStrip = new ViewPagerTabStrip(context);
142        addView(mTabStrip,
143                new FrameLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.MATCH_PARENT));
144        a.recycle();
145
146        if (CompatUtils.isLollipopCompatible()) {
147            // enable shadow casting from view bounds
148            setOutlineProvider(VIEW_BOUNDS_OUTLINE_PROVIDER);
149        }
150    }
151
152    public void setViewPager(ViewPager viewPager) {
153        mPager = viewPager;
154        addTabs(mPager.getAdapter());
155    }
156
157    /**
158     * Set the tab icons and initialize an array for unread counts the same length as the icon
159     * array.
160     *
161     * @param tabIcons An array representing the tab icons in order.
162     */
163    public void configureTabIcons(int[] tabIcons) {
164        mTabIcons = tabIcons;
165        mUnreadCounts = new int[tabIcons.length];
166    }
167
168    public void setUnreadCount(int count, int position) {
169        if (mUnreadCounts == null || position >= mUnreadCounts.length) {
170            return;
171        }
172        mUnreadCounts[position] = count;
173    }
174
175    private void addTabs(PagerAdapter adapter) {
176        mTabStrip.removeAllViews();
177
178        final int count = adapter.getCount();
179        for (int i = 0; i < count; i++) {
180            addTab(adapter.getPageTitle(i), i);
181        }
182    }
183
184    private void addTab(CharSequence tabTitle, final int position) {
185        View tabView;
186        if (mTabIcons != null && position < mTabIcons.length) {
187            View layout = LayoutInflater.from(getContext()).inflate(
188                    R.layout.unread_count_tab, null);
189            View iconView = layout.findViewById(R.id.icon);
190            iconView.setBackgroundResource(mTabIcons[position]);
191            iconView.setContentDescription(tabTitle);
192            TextView textView = (TextView) layout.findViewById(R.id.count);
193            if (mUnreadCounts != null && mUnreadCounts[position] > 0) {
194                textView.setText(Integer.toString(mUnreadCounts[position]));
195                textView.setVisibility(View.VISIBLE);
196                iconView.setContentDescription(getResources().getQuantityString(
197                        R.plurals.tab_title_with_unread_items,
198                        mUnreadCounts[position],
199                        tabTitle.toString(),
200                        mUnreadCounts[position]));
201            } else {
202                textView.setVisibility(View.INVISIBLE);
203                iconView.setContentDescription(tabTitle);
204            }
205            tabView = layout;
206        } else {
207            final TextView textView = new TextView(getContext());
208            textView.setText(tabTitle);
209            textView.setBackgroundResource(R.drawable.view_pager_tab_background);
210
211            // Assign various text appearance related attributes to child views.
212            if (mTextStyle > 0) {
213                textView.setTypeface(textView.getTypeface(), mTextStyle);
214            }
215            if (mTextSize > 0) {
216                textView.setTextSize(TypedValue.COMPLEX_UNIT_PX, mTextSize);
217            }
218            if (mTextColor != null) {
219                textView.setTextColor(mTextColor);
220            }
221            textView.setAllCaps(mTextAllCaps);
222            textView.setGravity(Gravity.CENTER);
223
224            tabView = textView;
225        }
226
227        tabView.setOnClickListener(new OnClickListener() {
228            @Override
229            public void onClick(View v) {
230                mPager.setCurrentItem(getRtlPosition(position));
231            }
232        });
233
234        tabView.setOnLongClickListener(new OnTabLongClickListener(position));
235
236        tabView.setPadding(mSidePadding, 0, mSidePadding, 0);
237
238        mTabStrip.addView(tabView, position, new LinearLayout.LayoutParams(
239                LayoutParams.WRAP_CONTENT, LayoutParams.MATCH_PARENT, 1));
240
241        // Default to the first child being selected
242        if (position == 0) {
243            mPrevSelected = 0;
244            tabView.setSelected(true);
245        }
246    }
247
248    /**
249     * Remove a tab at a certain index.
250     *
251     * @param index The index of the tab view we wish to remove.
252     */
253    public void removeTab(int index) {
254        View view = mTabStrip.getChildAt(index);
255        if (view != null) {
256            mTabStrip.removeView(view);
257        }
258    }
259
260    /**
261     * Refresh a tab at a certain index by removing it and reconstructing it.
262     *
263     * @param index The index of the tab view we wish to update.
264     */
265    public void updateTab(int index) {
266        removeTab(index);
267
268        if (index < mPager.getAdapter().getCount()) {
269            addTab(mPager.getAdapter().getPageTitle(index), index);
270        }
271    }
272
273    @Override
274    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
275        position = getRtlPosition(position);
276        int tabStripChildCount = mTabStrip.getChildCount();
277        if ((tabStripChildCount == 0) || (position < 0) || (position >= tabStripChildCount)) {
278            return;
279        }
280
281        mTabStrip.onPageScrolled(position, positionOffset, positionOffsetPixels);
282    }
283
284    @Override
285    public void onPageSelected(int position) {
286        position = getRtlPosition(position);
287        int tabStripChildCount = mTabStrip.getChildCount();
288        if ((tabStripChildCount == 0) || (position < 0) || (position >= tabStripChildCount)) {
289            return;
290        }
291
292        if (mPrevSelected >= 0 && mPrevSelected < tabStripChildCount) {
293            mTabStrip.getChildAt(mPrevSelected).setSelected(false);
294        }
295        final View selectedChild = mTabStrip.getChildAt(position);
296        selectedChild.setSelected(true);
297
298        // Update scroll position
299        final int scrollPos = selectedChild.getLeft() - (getWidth() - selectedChild.getWidth()) / 2;
300        smoothScrollTo(scrollPos, 0);
301        mPrevSelected = position;
302    }
303
304    @Override
305    public void onPageScrollStateChanged(int state) {
306    }
307
308    private int getRtlPosition(int position) {
309        if (getLayoutDirection() == View.LAYOUT_DIRECTION_RTL) {
310            return mTabStrip.getChildCount() - 1 - position;
311        }
312        return position;
313    }
314}
315
316