to top

实现横向导航

Lateral navigation is navigation between sibling screens in the application's screen hierarchy (sometimes referred to as a screen map). The most prominent lateral navigation patterns are tabs and horizontal paging (also known as swipe views). This pattern and others are described in 设计高效的导航. This lesson covers how to implement several of the primary lateral navigation patterns in Android.

Implement Tabs

Tabs allow the user to navigate between sibling screens by selecting the appropriate tab indicator available at the top of the display. In Android 3.0 and later, tabs are implemented using the ActionBar class, and are generally set up in Activity.onCreate(). In some cases, such as when horizontal space is limited and/or the number of tabs is large, an appropriate alternate presentation for tabs is a dropdown list (sometimes implemented using a Spinner).

In previous versions of Android, tabs could be implemented using a TabWidget and TabHost. For details, see the Hello, Views tutorial.

As of Android 3.0, however, you should use either NAVIGATION_MODE_TABS or NAVIGATION_MODE_LIST along with the ActionBar class.

Implement the Tabs Pattern with NAVIGATION_MODE_TABS

To create tabs, you can use the following code in your activity's onCreate() method. Note that the exact presentation of tabs may vary per device and by the current device configuration, to make best use of available screen space. For example, Android may automatically collapse tabs into a dropdown list if tabs don't fit horizontally in the action bar.

@Override
public void onCreate(Bundle savedInstanceState) {
    ...
    final ActionBar actionBar = getActionBar();

    // Specify that tabs should be displayed in the action bar.
    actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);

    // Create a tab listener that is called when the user changes tabs.
    ActionBar.TabListener tabListener = new ActionBar.TabListener() {
        public void onTabSelected(ActionBar.Tab tab,
                FragmentTransaction ft) { }

        public void onTabUnselected(ActionBar.Tab tab,
                FragmentTransaction ft) { }

        public void onTabReselected(ActionBar.Tab tab,
                FragmentTransaction ft) { }
    };

    // Add 3 tabs.
    for (int i = 0; i < 3; i++) {
        actionBar.addTab(
                actionBar.newTab()
                        .setText("Tab " + (i + 1))
                        .setTabListener(tabListener));
    }
    ...
}

Implement the Tabs Pattern with NAVIGATION_MODE_LIST

To use a dropdown list instead, use the following code in your activity's onCreate() method. Dropdown lists are often preferable in cases where more information must be shown per navigation item, such as unread message counts, or where the number of available navigation items is large.

@Override
public void onCreate(Bundle savedInstanceState) {
    ...
    final ActionBar actionBar = getActionBar();

    // Specify that a dropdown list should be displayed in the action bar.
    actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_LIST);

    actionBar.setListNavigationCallbacks(
            // Specify a SpinnerAdapter to populate the dropdown list.
            new ArrayAdapter(
                    actionBar.getThemedContext(),
                    android.R.layout.simple_list_item_1,
                    android.R.id.text1,
                    new String[]{ "Tab 1", "Tab 2", "Tab 3" }),

            // Provide a listener to be called when an item is selected.
            new ActionBar.OnNavigationListener() {
                public boolean onNavigationItemSelected(
                        int position, long id) {
                    // Take action here, e.g. switching to the
                    // corresponding fragment.
                    return true;
                }
            });
    ...
}

Implement Horizontal Paging (Swipe Views)

Horizontal paging, or swipe views, allow users to swipe horizontally on the current screen to navigate to adjacent screens. This pattern can be implemented using the ViewPager widget, currently available as part of the Android Support Package. For navigating between sibling screens representing a fixed number of sections, it's best to provide the ViewPager with a FragmentPagerAdapter. For horizontal paging across collections of objects, it's best to use a FragmentStatePagerAdapter, which destroys fragments as the user navigates to other pages, minimizing memory usage.

Below is an example of using a ViewPager to swipe across a collection of objects.

public class CollectionDemoActivity extends FragmentActivity {
    // When requested, this adapter returns a DemoObjectFragment,
    // representing an object in the collection.
    DemoCollectionPagerAdapter mDemoCollectionPagerAdapter;
    ViewPager mViewPager;

    public void onCreate(Bundle savedInstanceState) {
        // ViewPager and its adapters use support library
        // fragments, so use getSupportFragmentManager.
        mDemoCollectionPagerAdapter =
                new DemoCollectionPagerAdapter(
                        getSupportFragmentManager());
        mViewPager = (ViewPager) findViewById(R.id.pager);
        mViewPager.setAdapter(mDemoCollectionPagerAdapter);
    }
}

// Since this is an object collection, use a FragmentStatePagerAdapter,
// and NOT a FragmentPagerAdapter.
public class DemoCollectionPagerAdapter extends
        FragmentStatePagerAdapter {
    public DemoCollectionPagerAdapter(FragmentManager fm) {
        super(fm);
    }

    @Override
    public Fragment getItem(int i) {
        Fragment fragment = new DemoObjectFragment();
        Bundle args = new Bundle();
        // Our object is just an integer :-P
        args.putInt(DemoObjectFragment.ARG_OBJECT, i + 1);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public int getCount() {
        return 100;
    }

    @Override
    public CharSequence getPageTitle(int position) {
        return "OBJECT " + (position + 1);
    }
}

// Instances of this class are fragments representing a single
// object in our collection.
public static class DemoObjectFragment extends Fragment {
    public static final String ARG_OBJECT = "object";

    @Override
    public View onCreateView(LayoutInflater inflater,
            ViewGroup container, Bundle savedInstanceState) {
        // The last two arguments ensure LayoutParams are inflated
        // properly.
        View rootView = inflater.inflate(
                R.layout.fragment_collection_object, container, false);
        Bundle args = getArguments();
        ((TextView) rootView.findViewById(android.R.id.text1)).setText(
                Integer.toString(args.getInt(ARG_OBJECT)));
        return rootView;
    }
}

You can also add indicators to your horizontal paging UI by adding a PagerTitleStrip. Below is an example layout XML file for an activity whose entire contents are a ViewPager and a top-aligned PagerTitleStrip inside it. Individual pages (provided by the adapter) occupy the remaining space inside the ViewPager.

<android.support.v4.view.ViewPager
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/pager"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <android.support.v4.view.PagerTitleStrip
        android:id="@+id/pager_title_strip"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="top"
        android:background="#33b5e5"
        android:textColor="#fff"
        android:paddingTop="4dp"
        android:paddingBottom="4dp" />

</android.support.v4.view.ViewPager>

Implement Swiping Between Tabs

One of the key design recommendations in Android 4.0 for tabs is to allow swiping between them where appropriate. This behavior enables users to swipe horizontally across the selected tab's contents to navigate to adjacent tabs, without needed to directly interact with the tabs themselves. To implement this, you can use a ViewPager in conjunction with the ActionBar tabs API.

Upon observing the current page changing, select the corresponding tab. You can set up this behavior using an ViewPager.OnPageChangeListener in your activity's onCreate() method:

@Override
public void onCreate(Bundle savedInstanceState) {
    ...
    mViewPager.setOnPageChangeListener(
            new ViewPager.SimpleOnPageChangeListener() {
                @Override
                public void onPageSelected(int position) {
                    // When swiping between pages, select the
                    // corresponding tab.
                    getActionBar().setSelectedNavigationItem(position);
                }
            });
    ...
}

And upon selecting a tab, switch to the corresponding page in the ViewPager. To do this, add an ActionBar.TabListener to your tab when creating it using the newTab() method:

actionBar.newTab()
        ...
        .setTabListener(new ActionBar.TabListener() {
            public void onTabSelected(ActionBar.Tab tab,
                    FragmentTransaction ft) {
                // When the tab is selected, switch to the
                // corresponding page in the ViewPager.
                mViewPager.setCurrentItem(tab.getPosition());
            }
            ...
        }));