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 17 package android.widget; 18 19 import com.android.internal.R; 20 21 import android.app.LocalActivityManager; 22 import android.content.Context; 23 import android.content.Intent; 24 import android.content.res.TypedArray; 25 import android.graphics.drawable.Drawable; 26 import android.os.Build; 27 import android.text.TextUtils; 28 import android.util.AttributeSet; 29 import android.view.KeyEvent; 30 import android.view.LayoutInflater; 31 import android.view.SoundEffectConstants; 32 import android.view.View; 33 import android.view.ViewGroup; 34 import android.view.ViewTreeObserver; 35 import android.view.Window; 36 37 import java.util.ArrayList; 38 import java.util.List; 39 40 /** 41 * Container for a tabbed window view. This object holds two children: a set of tab labels that the 42 * user clicks to select a specific tab, and a FrameLayout object that displays the contents of that 43 * page. The individual elements are typically controlled using this container object, rather than 44 * setting values on the child elements themselves. 45 * 46 * <p>See the <a href="{@docRoot}resources/tutorials/views/hello-tabwidget.html">Tab Layout 47 * tutorial</a>.</p> 48 */ 49 public class TabHost extends FrameLayout implements ViewTreeObserver.OnTouchModeChangeListener { 50 51 private TabWidget mTabWidget; 52 private FrameLayout mTabContent; 53 private List<TabSpec> mTabSpecs = new ArrayList<TabSpec>(2); 54 /** 55 * This field should be made private, so it is hidden from the SDK. 56 * {@hide} 57 */ 58 protected int mCurrentTab = -1; 59 private View mCurrentView = null; 60 /** 61 * This field should be made private, so it is hidden from the SDK. 62 * {@hide} 63 */ 64 protected LocalActivityManager mLocalActivityManager = null; 65 private OnTabChangeListener mOnTabChangeListener; 66 private OnKeyListener mTabKeyListener; 67 68 private int mTabLayoutId; 69 TabHost(Context context)70 public TabHost(Context context) { 71 super(context); 72 initTabHost(); 73 } 74 TabHost(Context context, AttributeSet attrs)75 public TabHost(Context context, AttributeSet attrs) { 76 super(context, attrs); 77 78 TypedArray a = context.obtainStyledAttributes(attrs, 79 com.android.internal.R.styleable.TabWidget, 80 com.android.internal.R.attr.tabWidgetStyle, 0); 81 82 mTabLayoutId = a.getResourceId(R.styleable.TabWidget_tabLayout, 0); 83 a.recycle(); 84 85 if (mTabLayoutId == 0) { 86 // In case the tabWidgetStyle does not inherit from Widget.TabWidget and tabLayout is 87 // not defined. 88 mTabLayoutId = R.layout.tab_indicator_holo; 89 } 90 91 initTabHost(); 92 } 93 initTabHost()94 private void initTabHost() { 95 setFocusableInTouchMode(true); 96 setDescendantFocusability(FOCUS_AFTER_DESCENDANTS); 97 98 mCurrentTab = -1; 99 mCurrentView = null; 100 } 101 102 /** 103 * Get a new {@link TabSpec} associated with this tab host. 104 * @param tag required tag of tab. 105 */ newTabSpec(String tag)106 public TabSpec newTabSpec(String tag) { 107 return new TabSpec(tag); 108 } 109 110 111 112 /** 113 * <p>Call setup() before adding tabs if loading TabHost using findViewById(). 114 * <i><b>However</i></b>: You do not need to call setup() after getTabHost() 115 * in {@link android.app.TabActivity TabActivity}. 116 * Example:</p> 117 <pre>mTabHost = (TabHost)findViewById(R.id.tabhost); 118 mTabHost.setup(); 119 mTabHost.addTab(TAB_TAG_1, "Hello, world!", "Tab 1"); 120 */ setup()121 public void setup() { 122 mTabWidget = (TabWidget) findViewById(com.android.internal.R.id.tabs); 123 if (mTabWidget == null) { 124 throw new RuntimeException( 125 "Your TabHost must have a TabWidget whose id attribute is 'android.R.id.tabs'"); 126 } 127 128 // KeyListener to attach to all tabs. Detects non-navigation keys 129 // and relays them to the tab content. 130 mTabKeyListener = new OnKeyListener() { 131 public boolean onKey(View v, int keyCode, KeyEvent event) { 132 switch (keyCode) { 133 case KeyEvent.KEYCODE_DPAD_CENTER: 134 case KeyEvent.KEYCODE_DPAD_LEFT: 135 case KeyEvent.KEYCODE_DPAD_RIGHT: 136 case KeyEvent.KEYCODE_DPAD_UP: 137 case KeyEvent.KEYCODE_DPAD_DOWN: 138 case KeyEvent.KEYCODE_ENTER: 139 return false; 140 141 } 142 mTabContent.requestFocus(View.FOCUS_FORWARD); 143 return mTabContent.dispatchKeyEvent(event); 144 } 145 146 }; 147 148 mTabWidget.setTabSelectionListener(new TabWidget.OnTabSelectionChanged() { 149 public void onTabSelectionChanged(int tabIndex, boolean clicked) { 150 setCurrentTab(tabIndex); 151 if (clicked) { 152 mTabContent.requestFocus(View.FOCUS_FORWARD); 153 } 154 } 155 }); 156 157 mTabContent = (FrameLayout) findViewById(com.android.internal.R.id.tabcontent); 158 if (mTabContent == null) { 159 throw new RuntimeException( 160 "Your TabHost must have a FrameLayout whose id attribute is " 161 + "'android.R.id.tabcontent'"); 162 } 163 } 164 165 @Override sendAccessibilityEvent(int eventType)166 public void sendAccessibilityEvent(int eventType) { 167 /* avoid super class behavior - TabWidget sends the right events */ 168 } 169 170 /** 171 * If you are using {@link TabSpec#setContent(android.content.Intent)}, this 172 * must be called since the activityGroup is needed to launch the local activity. 173 * 174 * This is done for you if you extend {@link android.app.TabActivity}. 175 * @param activityGroup Used to launch activities for tab content. 176 */ setup(LocalActivityManager activityGroup)177 public void setup(LocalActivityManager activityGroup) { 178 setup(); 179 mLocalActivityManager = activityGroup; 180 } 181 182 183 @Override onAttachedToWindow()184 protected void onAttachedToWindow() { 185 super.onAttachedToWindow(); 186 final ViewTreeObserver treeObserver = getViewTreeObserver(); 187 treeObserver.addOnTouchModeChangeListener(this); 188 } 189 190 @Override onDetachedFromWindow()191 protected void onDetachedFromWindow() { 192 super.onDetachedFromWindow(); 193 final ViewTreeObserver treeObserver = getViewTreeObserver(); 194 treeObserver.removeOnTouchModeChangeListener(this); 195 } 196 197 /** 198 * {@inheritDoc} 199 */ onTouchModeChanged(boolean isInTouchMode)200 public void onTouchModeChanged(boolean isInTouchMode) { 201 if (!isInTouchMode) { 202 // leaving touch mode.. if nothing has focus, let's give it to 203 // the indicator of the current tab 204 if (mCurrentView != null && (!mCurrentView.hasFocus() || mCurrentView.isFocused())) { 205 mTabWidget.getChildTabViewAt(mCurrentTab).requestFocus(); 206 } 207 } 208 } 209 210 /** 211 * Add a tab. 212 * @param tabSpec Specifies how to create the indicator and content. 213 */ addTab(TabSpec tabSpec)214 public void addTab(TabSpec tabSpec) { 215 216 if (tabSpec.mIndicatorStrategy == null) { 217 throw new IllegalArgumentException("you must specify a way to create the tab indicator."); 218 } 219 220 if (tabSpec.mContentStrategy == null) { 221 throw new IllegalArgumentException("you must specify a way to create the tab content"); 222 } 223 View tabIndicator = tabSpec.mIndicatorStrategy.createIndicatorView(); 224 tabIndicator.setOnKeyListener(mTabKeyListener); 225 226 // If this is a custom view, then do not draw the bottom strips for 227 // the tab indicators. 228 if (tabSpec.mIndicatorStrategy instanceof ViewIndicatorStrategy) { 229 mTabWidget.setStripEnabled(false); 230 } 231 232 mTabWidget.addView(tabIndicator); 233 mTabSpecs.add(tabSpec); 234 235 if (mCurrentTab == -1) { 236 setCurrentTab(0); 237 } 238 } 239 240 241 /** 242 * Removes all tabs from the tab widget associated with this tab host. 243 */ clearAllTabs()244 public void clearAllTabs() { 245 mTabWidget.removeAllViews(); 246 initTabHost(); 247 mTabContent.removeAllViews(); 248 mTabSpecs.clear(); 249 requestLayout(); 250 invalidate(); 251 } 252 getTabWidget()253 public TabWidget getTabWidget() { 254 return mTabWidget; 255 } 256 getCurrentTab()257 public int getCurrentTab() { 258 return mCurrentTab; 259 } 260 getCurrentTabTag()261 public String getCurrentTabTag() { 262 if (mCurrentTab >= 0 && mCurrentTab < mTabSpecs.size()) { 263 return mTabSpecs.get(mCurrentTab).getTag(); 264 } 265 return null; 266 } 267 getCurrentTabView()268 public View getCurrentTabView() { 269 if (mCurrentTab >= 0 && mCurrentTab < mTabSpecs.size()) { 270 return mTabWidget.getChildTabViewAt(mCurrentTab); 271 } 272 return null; 273 } 274 getCurrentView()275 public View getCurrentView() { 276 return mCurrentView; 277 } 278 setCurrentTabByTag(String tag)279 public void setCurrentTabByTag(String tag) { 280 int i; 281 for (i = 0; i < mTabSpecs.size(); i++) { 282 if (mTabSpecs.get(i).getTag().equals(tag)) { 283 setCurrentTab(i); 284 break; 285 } 286 } 287 } 288 289 /** 290 * Get the FrameLayout which holds tab content 291 */ getTabContentView()292 public FrameLayout getTabContentView() { 293 return mTabContent; 294 } 295 296 @Override dispatchKeyEvent(KeyEvent event)297 public boolean dispatchKeyEvent(KeyEvent event) { 298 final boolean handled = super.dispatchKeyEvent(event); 299 300 // unhandled key ups change focus to tab indicator for embedded activities 301 // when there is nothing that will take focus from default focus searching 302 if (!handled 303 && (event.getAction() == KeyEvent.ACTION_DOWN) 304 && (event.getKeyCode() == KeyEvent.KEYCODE_DPAD_UP) 305 && (mCurrentView != null) 306 && (mCurrentView.isRootNamespace()) 307 && (mCurrentView.hasFocus()) 308 && (mCurrentView.findFocus().focusSearch(View.FOCUS_UP) == null)) { 309 mTabWidget.getChildTabViewAt(mCurrentTab).requestFocus(); 310 playSoundEffect(SoundEffectConstants.NAVIGATION_UP); 311 return true; 312 } 313 return handled; 314 } 315 316 317 @Override dispatchWindowFocusChanged(boolean hasFocus)318 public void dispatchWindowFocusChanged(boolean hasFocus) { 319 if (mCurrentView != null){ 320 mCurrentView.dispatchWindowFocusChanged(hasFocus); 321 } 322 } 323 setCurrentTab(int index)324 public void setCurrentTab(int index) { 325 if (index < 0 || index >= mTabSpecs.size()) { 326 return; 327 } 328 329 if (index == mCurrentTab) { 330 return; 331 } 332 333 // notify old tab content 334 if (mCurrentTab != -1) { 335 mTabSpecs.get(mCurrentTab).mContentStrategy.tabClosed(); 336 } 337 338 mCurrentTab = index; 339 final TabHost.TabSpec spec = mTabSpecs.get(index); 340 341 // Call the tab widget's focusCurrentTab(), instead of just 342 // selecting the tab. 343 mTabWidget.focusCurrentTab(mCurrentTab); 344 345 // tab content 346 mCurrentView = spec.mContentStrategy.getContentView(); 347 348 if (mCurrentView.getParent() == null) { 349 mTabContent 350 .addView( 351 mCurrentView, 352 new ViewGroup.LayoutParams( 353 ViewGroup.LayoutParams.MATCH_PARENT, 354 ViewGroup.LayoutParams.MATCH_PARENT)); 355 } 356 357 if (!mTabWidget.hasFocus()) { 358 // if the tab widget didn't take focus (likely because we're in touch mode) 359 // give the current tab content view a shot 360 mCurrentView.requestFocus(); 361 } 362 363 //mTabContent.requestFocus(View.FOCUS_FORWARD); 364 invokeOnTabChangeListener(); 365 } 366 367 /** 368 * Register a callback to be invoked when the selected state of any of the items 369 * in this list changes 370 * @param l 371 * The callback that will run 372 */ setOnTabChangedListener(OnTabChangeListener l)373 public void setOnTabChangedListener(OnTabChangeListener l) { 374 mOnTabChangeListener = l; 375 } 376 invokeOnTabChangeListener()377 private void invokeOnTabChangeListener() { 378 if (mOnTabChangeListener != null) { 379 mOnTabChangeListener.onTabChanged(getCurrentTabTag()); 380 } 381 } 382 383 /** 384 * Interface definition for a callback to be invoked when tab changed 385 */ 386 public interface OnTabChangeListener { onTabChanged(String tabId)387 void onTabChanged(String tabId); 388 } 389 390 391 /** 392 * Makes the content of a tab when it is selected. Use this if your tab 393 * content needs to be created on demand, i.e. you are not showing an 394 * existing view or starting an activity. 395 */ 396 public interface TabContentFactory { 397 /** 398 * Callback to make the tab contents 399 * 400 * @param tag 401 * Which tab was selected. 402 * @return The view to display the contents of the selected tab. 403 */ createTabContent(String tag)404 View createTabContent(String tag); 405 } 406 407 408 /** 409 * A tab has a tab indicator, content, and a tag that is used to keep 410 * track of it. This builder helps choose among these options. 411 * 412 * For the tab indicator, your choices are: 413 * 1) set a label 414 * 2) set a label and an icon 415 * 416 * For the tab content, your choices are: 417 * 1) the id of a {@link View} 418 * 2) a {@link TabContentFactory} that creates the {@link View} content. 419 * 3) an {@link Intent} that launches an {@link android.app.Activity}. 420 */ 421 public class TabSpec { 422 423 private String mTag; 424 425 private IndicatorStrategy mIndicatorStrategy; 426 private ContentStrategy mContentStrategy; 427 TabSpec(String tag)428 private TabSpec(String tag) { 429 mTag = tag; 430 } 431 432 /** 433 * Specify a label as the tab indicator. 434 */ setIndicator(CharSequence label)435 public TabSpec setIndicator(CharSequence label) { 436 mIndicatorStrategy = new LabelIndicatorStrategy(label); 437 return this; 438 } 439 440 /** 441 * Specify a label and icon as the tab indicator. 442 */ setIndicator(CharSequence label, Drawable icon)443 public TabSpec setIndicator(CharSequence label, Drawable icon) { 444 mIndicatorStrategy = new LabelAndIconIndicatorStrategy(label, icon); 445 return this; 446 } 447 448 /** 449 * Specify a view as the tab indicator. 450 */ setIndicator(View view)451 public TabSpec setIndicator(View view) { 452 mIndicatorStrategy = new ViewIndicatorStrategy(view); 453 return this; 454 } 455 456 /** 457 * Specify the id of the view that should be used as the content 458 * of the tab. 459 */ setContent(int viewId)460 public TabSpec setContent(int viewId) { 461 mContentStrategy = new ViewIdContentStrategy(viewId); 462 return this; 463 } 464 465 /** 466 * Specify a {@link android.widget.TabHost.TabContentFactory} to use to 467 * create the content of the tab. 468 */ setContent(TabContentFactory contentFactory)469 public TabSpec setContent(TabContentFactory contentFactory) { 470 mContentStrategy = new FactoryContentStrategy(mTag, contentFactory); 471 return this; 472 } 473 474 /** 475 * Specify an intent to use to launch an activity as the tab content. 476 */ setContent(Intent intent)477 public TabSpec setContent(Intent intent) { 478 mContentStrategy = new IntentContentStrategy(mTag, intent); 479 return this; 480 } 481 482 getTag()483 public String getTag() { 484 return mTag; 485 } 486 } 487 488 /** 489 * Specifies what you do to create a tab indicator. 490 */ 491 private static interface IndicatorStrategy { 492 493 /** 494 * Return the view for the indicator. 495 */ createIndicatorView()496 View createIndicatorView(); 497 } 498 499 /** 500 * Specifies what you do to manage the tab content. 501 */ 502 private static interface ContentStrategy { 503 504 /** 505 * Return the content view. The view should may be cached locally. 506 */ getContentView()507 View getContentView(); 508 509 /** 510 * Perhaps do something when the tab associated with this content has 511 * been closed (i.e make it invisible, or remove it). 512 */ tabClosed()513 void tabClosed(); 514 } 515 516 /** 517 * How to create a tab indicator that just has a label. 518 */ 519 private class LabelIndicatorStrategy implements IndicatorStrategy { 520 521 private final CharSequence mLabel; 522 LabelIndicatorStrategy(CharSequence label)523 private LabelIndicatorStrategy(CharSequence label) { 524 mLabel = label; 525 } 526 createIndicatorView()527 public View createIndicatorView() { 528 final Context context = getContext(); 529 LayoutInflater inflater = 530 (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); 531 View tabIndicator = inflater.inflate(mTabLayoutId, 532 mTabWidget, // tab widget is the parent 533 false); // no inflate params 534 535 final TextView tv = (TextView) tabIndicator.findViewById(R.id.title); 536 tv.setText(mLabel); 537 538 if (context.getApplicationInfo().targetSdkVersion <= Build.VERSION_CODES.DONUT) { 539 // Donut apps get old color scheme 540 tabIndicator.setBackgroundResource(R.drawable.tab_indicator_v4); 541 tv.setTextColor(context.getResources().getColorStateList(R.color.tab_indicator_text_v4)); 542 } 543 544 return tabIndicator; 545 } 546 } 547 548 /** 549 * How we create a tab indicator that has a label and an icon 550 */ 551 private class LabelAndIconIndicatorStrategy implements IndicatorStrategy { 552 553 private final CharSequence mLabel; 554 private final Drawable mIcon; 555 LabelAndIconIndicatorStrategy(CharSequence label, Drawable icon)556 private LabelAndIconIndicatorStrategy(CharSequence label, Drawable icon) { 557 mLabel = label; 558 mIcon = icon; 559 } 560 createIndicatorView()561 public View createIndicatorView() { 562 final Context context = getContext(); 563 LayoutInflater inflater = 564 (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); 565 View tabIndicator = inflater.inflate(mTabLayoutId, 566 mTabWidget, // tab widget is the parent 567 false); // no inflate params 568 569 final TextView tv = (TextView) tabIndicator.findViewById(R.id.title); 570 final ImageView iconView = (ImageView) tabIndicator.findViewById(R.id.icon); 571 572 // when icon is gone by default, we're in exclusive mode 573 final boolean exclusive = iconView.getVisibility() == View.GONE; 574 final boolean bindIcon = !exclusive || TextUtils.isEmpty(mLabel); 575 576 tv.setText(mLabel); 577 578 if (bindIcon && mIcon != null) { 579 iconView.setImageDrawable(mIcon); 580 iconView.setVisibility(VISIBLE); 581 } 582 583 if (context.getApplicationInfo().targetSdkVersion <= Build.VERSION_CODES.DONUT) { 584 // Donut apps get old color scheme 585 tabIndicator.setBackgroundResource(R.drawable.tab_indicator_v4); 586 tv.setTextColor(context.getResources().getColorStateList(R.color.tab_indicator_text_v4)); 587 } 588 589 return tabIndicator; 590 } 591 } 592 593 /** 594 * How to create a tab indicator by specifying a view. 595 */ 596 private class ViewIndicatorStrategy implements IndicatorStrategy { 597 598 private final View mView; 599 ViewIndicatorStrategy(View view)600 private ViewIndicatorStrategy(View view) { 601 mView = view; 602 } 603 createIndicatorView()604 public View createIndicatorView() { 605 return mView; 606 } 607 } 608 609 /** 610 * How to create the tab content via a view id. 611 */ 612 private class ViewIdContentStrategy implements ContentStrategy { 613 614 private final View mView; 615 ViewIdContentStrategy(int viewId)616 private ViewIdContentStrategy(int viewId) { 617 mView = mTabContent.findViewById(viewId); 618 if (mView != null) { 619 mView.setVisibility(View.GONE); 620 } else { 621 throw new RuntimeException("Could not create tab content because " + 622 "could not find view with id " + viewId); 623 } 624 } 625 getContentView()626 public View getContentView() { 627 mView.setVisibility(View.VISIBLE); 628 return mView; 629 } 630 tabClosed()631 public void tabClosed() { 632 mView.setVisibility(View.GONE); 633 } 634 } 635 636 /** 637 * How tab content is managed using {@link TabContentFactory}. 638 */ 639 private class FactoryContentStrategy implements ContentStrategy { 640 private View mTabContent; 641 private final CharSequence mTag; 642 private TabContentFactory mFactory; 643 FactoryContentStrategy(CharSequence tag, TabContentFactory factory)644 public FactoryContentStrategy(CharSequence tag, TabContentFactory factory) { 645 mTag = tag; 646 mFactory = factory; 647 } 648 getContentView()649 public View getContentView() { 650 if (mTabContent == null) { 651 mTabContent = mFactory.createTabContent(mTag.toString()); 652 } 653 mTabContent.setVisibility(View.VISIBLE); 654 return mTabContent; 655 } 656 tabClosed()657 public void tabClosed() { 658 mTabContent.setVisibility(View.GONE); 659 } 660 } 661 662 /** 663 * How tab content is managed via an {@link Intent}: the content view is the 664 * decorview of the launched activity. 665 */ 666 private class IntentContentStrategy implements ContentStrategy { 667 668 private final String mTag; 669 private final Intent mIntent; 670 671 private View mLaunchedView; 672 IntentContentStrategy(String tag, Intent intent)673 private IntentContentStrategy(String tag, Intent intent) { 674 mTag = tag; 675 mIntent = intent; 676 } 677 getContentView()678 public View getContentView() { 679 if (mLocalActivityManager == null) { 680 throw new IllegalStateException("Did you forget to call 'public void setup(LocalActivityManager activityGroup)'?"); 681 } 682 final Window w = mLocalActivityManager.startActivity( 683 mTag, mIntent); 684 final View wd = w != null ? w.getDecorView() : null; 685 if (mLaunchedView != wd && mLaunchedView != null) { 686 if (mLaunchedView.getParent() != null) { 687 mTabContent.removeView(mLaunchedView); 688 } 689 } 690 mLaunchedView = wd; 691 692 // XXX Set FOCUS_AFTER_DESCENDANTS on embedded activities for now so they can get 693 // focus if none of their children have it. They need focus to be able to 694 // display menu items. 695 // 696 // Replace this with something better when Bug 628886 is fixed... 697 // 698 if (mLaunchedView != null) { 699 mLaunchedView.setVisibility(View.VISIBLE); 700 mLaunchedView.setFocusableInTouchMode(true); 701 ((ViewGroup) mLaunchedView).setDescendantFocusability( 702 FOCUS_AFTER_DESCENDANTS); 703 } 704 return mLaunchedView; 705 } 706 tabClosed()707 public void tabClosed() { 708 if (mLaunchedView != null) { 709 mLaunchedView.setVisibility(View.GONE); 710 } 711 } 712 } 713 714 } 715