1 /* 2 * Copyright 2012 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 com.example.android.tabcompat.lib; 18 19 import android.app.ActionBar; 20 import android.os.Bundle; 21 import android.support.v4.app.Fragment; 22 import android.support.v4.app.FragmentActivity; 23 import android.support.v4.app.FragmentTransaction; 24 25 /** 26 * Helper class to build tabs on Honeycomb. Call {@link TabCompatActivity#getTabHelper()} 27 * to get the generic instance for compatibility with older versions. 28 */ 29 public class TabHelperHoneycomb extends TabHelper { 30 31 ActionBar mActionBar; 32 33 protected TabHelperHoneycomb(FragmentActivity activity) { 34 super(activity); 35 } 36 37 @Override 38 protected void setUp() { 39 if (mActionBar == null) { 40 mActionBar = mActivity.getActionBar(); 41 mActionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS); 42 } 43 } 44 45 @Override 46 public void addTab(CompatTab tab) { 47 String tag = tab.getTag(); 48 49 // Check to see if we already have a fragment for this tab, probably 50 // from a previously saved state. If so, deactivate it, because our 51 // initial state is that a tab isn't shown. 52 53 Fragment fragment = mActivity.getSupportFragmentManager().findFragmentByTag(tag); 54 tab.setFragment(fragment); 55 56 if (fragment != null && !fragment.isDetached()) { 57 FragmentTransaction ft = mActivity.getSupportFragmentManager().beginTransaction(); 58 ft.detach(fragment); 59 ft.commit(); 60 } 61 62 if (tab.getCallback() == null) { 63 throw new IllegalStateException("CompatTab must have a CompatTabListener"); 64 } 65 66 // We know tab is a CompatTabHoneycomb instance, so its 67 // native tab object is an ActionBar.Tab. 68 mActionBar.addTab((ActionBar.Tab) tab.getTab()); 69 } 70 71 @Override 72 protected void onSaveInstanceState(Bundle outState) { 73 int position = mActionBar.getSelectedTab().getPosition(); 74 outState.putInt("tab_position", position); 75 } 76 77 @Override 78 protected void onRestoreInstanceState(Bundle savedInstanceState) { 79 int position = savedInstanceState.getInt("tab_position"); 80 mActionBar.setSelectedNavigationItem(position); 81 } 82 } 83