Android Use Tab with new ToolBar (AppCompat v7-21)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26540078/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-20 11:45:45  来源:igfitidea点击:

Use Tab with new ToolBar (AppCompat v7-21)

androidtabsandroid-support-libraryandroid-appcompatandroid-actionbar-compat

提问by Leandro Hoffmann

I was using SupportActionBar with tabs and a custom ActionBar theme (created with http://jgilfelt.github.io/android-actionbarstylegenerator/), that show the tabs only when the user expands the search view.

I was using SupportActionBar with tabs and a custom ActionBar theme (created with http://jgilfelt.github.io/android-actionbarstylegenerator/), that show the tabs only when the user expands the search view.

public boolean onMenuItemActionExpand(MenuItem item) {
        actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
        return true;
    }
}

I migrated from ActionBar to Toolbar. My app really needs to support API 9.

I migrated from ActionBar to Toolbar. My app really needs to support API 9.

Is there a way to use this code to add the tabs back?:

Is there a way to use this code to add the tabs back?:

Toolbar toolbar = (Toolbar) findViewById(R.id.new_actionbar);
setSupportActionBar(toolbar);
getSupportActionBar().setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);

If possible, how can I use my custom theme or style the toolbar?

If possible, how can I use my custom theme or style the toolbar?

The documentation says that this is deprecated and suggests using a different type of navigation. But I don't know of any other components in Android that have the same functionality.

The documentation says that this is deprecated and suggests using a different type of navigation. But I don't know of any other components in Android that have the same functionality.

Some help?

Some help?

回答by Gabriele Mariotti

With the API 21 the method setNavigationMode(ActionBar.NAVIGATION_MODE_TABS)is deprecated.

With the API 21 the method setNavigationMode(ActionBar.NAVIGATION_MODE_TABS)is deprecated.

UPDATE 01/08/2019 (Material Components Library)

UPDATE 01/08/2019 (Material Components Library)

Add the dependency to your build.gradle:

Add the dependency to your build.gradle:

dependencies { implementation ‘com.google.android.material:material:1.1.0' }

Then you can use the new TabLayout.

Then you can use the new TabLayout.

<androidx.constraintlayout.widget.ConstraintLayout>

     <com.google.android.material.appbar.AppBarLayout   ...>

        <androidx.appcompat.widget.Toolbar  .../>


        <com.google.android.material.tabs.TabLayout
         ...
         />

     </com.google.android.material.appbar.AppBarLayout>

     <androidx.viewpager.widget.ViewPager 
        android:id="@+id/viewpager"
        app:layout_behavior="@string/appbar_scrolling_view_behavior" />

</androidx.constraintlayout.widget.ConstraintLayout>

The code is simple:

The code is simple:

TabLayout tabs = (TabLayout) findViewById(R.id.tabs);
tabs.setupWithViewPager(pager);


UPDATE 29/05/2015 (Support Library)

UPDATE 29/05/2015 (Support Library)

With the new Design Support Librarynow you can use the TabLayout.

With the new Design Support Librarynow you can use the TabLayout.

Just add this dependency to your build.gradle

Just add this dependency to your build.gradle

compile 'com.android.support:design:22.2.0'

The code is very simple:

The code is very simple:

TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
        tabLayout.setupWithViewPager(viewPager);

To implement many of the features of material designs you should use it within a CoordinatorLayoutand a AppBarLayout.

To implement many of the features of material designs you should use it within a CoordinatorLayoutand a AppBarLayout.

Something like this:

Something like this:

 <android.support.design.widget.CoordinatorLayout
         xmlns:android="http://schemas.android.com/apk/res/android"
         xmlns:app="http://schemas.android.com/apk/res-auto"
         android:layout_width="match_parent"
         android:layout_height="match_parent">


     <android.support.design.widget.AppBarLayout
             android:layout_height="wrap_content"
             android:layout_width="match_parent">

         <android.support.v7.widget.Toolbar
                 ...
                 app:layout_scrollFlags="scroll|enterAlways"/>

         <android.support.design.widget.TabLayout
                 ...
                 app:layout_scrollFlags="scroll|enterAlways"/>

     </android.support.design.widget.AppBarLayout>

     <android.support.v4.view.ViewPager
        android:id="@+id/viewpager"
        app:layout_behavior="@string/appbar_scrolling_view_behavior" />

 </android.support.design.widget.CoordinatorLayout>


OLD

OLD

You can use a different pattern. For example you can use the same example that you can see in googleio14.

You can use a different pattern. For example you can use the same example that you can see in googleio14.

It uses a SlidingTabLayoutwhich works with a ViewPager.

It uses a SlidingTabLayoutwhich works with a ViewPager.

Here you can find the example(it is in your sdk example)

Here you can find the example(it is in your sdk example)

Here you can find the Google io14 example:

Here you can find the Google io14 example:

回答by Farbod Salamat-Zadeh

Although probably a little late to answer this question now, I realised that I wrote an answer on a similar questionwhich covers both using the Design Support Library and prior to Google I/O.

Although probably a little late to answer this question now, I realised that I wrote an answer on a similar questionwhich covers both using the Design Support Library and prior to Google I/O.

I have included the essential parts below:

I have included the essential parts below:



Using a TabLayoutwith the Toolbarhas become much simpler since the announcement of the Android Design Support Librarymeaning we no longer need to download custom view classes.

Using a TabLayoutwith the Toolbarhas become much simpler since the announcement of the Android Design Support Librarymeaning we no longer need to download custom view classes.

From the Android Developers' Blogspot post on the Android Design Support Library:

From the Android Developers' Blogspot post on the Android Design Support Library:

Tabs:

Switching between different views in your app via tabsis not a new concept to material design and they are equally at home as a top level navigation patternor for organizing different groupings of content within your app (say, different genres of music).

The Design library's TabLayoutimplements both fixed tabs, where the view's width is divided equally between all of the tabs, as well as scrollable tabs, where the tabs are not a uniform size and can scroll horizontally. Tabs can be added programmatically:

TabLayout tabLayout = ...;
tabLayout.addTab(tabLayout.newTab().setText("Tab 1"));

However, if you are using a ViewPagerfor horizontal paging between tabs, you can create tabs directly from your PagerAdapter's getPageTitle()and then connect the two together using setupWithViewPager(). This ensures that tab selection events update the ViewPager and page changes update the selected tab.

Tabs:

Switching between different views in your app via tabsis not a new concept to material design and they are equally at home as a top level navigation patternor for organizing different groupings of content within your app (say, different genres of music).

The Design library's TabLayoutimplements both fixed tabs, where the view's width is divided equally between all of the tabs, as well as scrollable tabs, where the tabs are not a uniform size and can scroll horizontally. Tabs can be added programmatically:

TabLayout tabLayout = ...;
tabLayout.addTab(tabLayout.newTab().setText("Tab 1"));

However, if you are using a ViewPagerfor horizontal paging between tabs, you can create tabs directly from your PagerAdapter's getPageTitle()and then connect the two together using setupWithViewPager(). This ensures that tab selection events update the ViewPager and page changes update the selected tab.



If you are not using the Design Support library, you will instead need to do the following:

If you are not using the Design Support library, you will instead need to do the following:

1.Download the SlidingTabLayout.javaand SlidingTabStrip.javafiles from Google's I/O Conference app on GitHub. These would be the views that would be used in the tab layout, so I created a folder with my other Java activities called 'view' and placed them there.

1.Download the SlidingTabLayout.javaand SlidingTabStrip.javafiles from Google's I/O Conference app on GitHub. These would be the views that would be used in the tab layout, so I created a folder with my other Java activities called 'view' and placed them there.

2.Edit your layout to include the SlidingTabLayout:

2.Edit your layout to include the SlidingTabLayout:

<LinearLayout
    android:orientation="vertical"
    ... >

    <!-- This is the Toolbar with the tabs underneath -->
    <LinearLayout
        android:orientation="vertical"
        ... >

        <include android:id="@+id/my_toolbar" layout="@layout/toolbar" />

        <com.mycompany.myapp.SlidingTabLayout
            android:id="@+id/sliding_tabs"
            android:background="?attr/colorPrimary"
            android:layout_width="match_parent"
            android:layout_height="wrap_content" />
    </LinearLayout>

    <!-- This is the ViewPager (which you already should have if you have
        used tabs before) -->
    <android.support.v4.view.ViewPager
        android:id="@+id/view_pager"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

    ...

</LinearLayout>

The line which references the Toolbar(<include android:id="@+id/detail_toolbar" layout="@layout/toolbar" />), is referencing another XML file I had used to make the Toolbar.

The line which references the Toolbar(<include android:id="@+id/detail_toolbar" layout="@layout/toolbar" />), is referencing another XML file I had used to make the Toolbar.

3.Change the package names in SlidingTabLayout.javaand SlidingTabStrip.javacorresponding to where they were placed. In my case, I used something similar to: package com.mycompany.myapp.view;for both of these files. Organise imports and add in any necessary, as noted by the IDE you are using.

3.Change the package names in SlidingTabLayout.javaand SlidingTabStrip.javacorresponding to where they were placed. In my case, I used something similar to: package com.mycompany.myapp.view;for both of these files. Organise imports and add in any necessary, as noted by the IDE you are using.

4.In your Activity(which was extending AppCompatActivity), setup the Toolbarin the onCreatemethod:

4.In your Activity(which was extending AppCompatActivity), setup the Toolbarin the onCreatemethod:

Toolbar toolbar = (Toolbar) findViewById(R.id.detail_toolbar);
setSupportActionBar(toolbar);

5.Setup the ViewPagerand SlidingTabLayoutparts:

5.Setup the ViewPagerand SlidingTabLayoutparts:

mViewPager = (ViewPager) findViewById(R.id.view_pager);
mViewPager.setAdapter(new ViewPagerAdapter(getSupportFragmentManager()));
mSlidingTabLayout = (SlidingTabLayout) findViewById(R.id.sliding_tabs);
mSlidingTabLayout.setSelectedIndicatorColors(getResources().getColor(R.color.tab_line));   
mSlidingTabLayout.setDistributeEvenly(true);
mSlidingTabLayout.setViewPager(mViewPager);

The colour 'tab_line' was a colour I had declared in color.xmlwhich would be the colour of the tab line indicator. Also note that the variables above were global which I defined previously in this activity:

The colour 'tab_line' was a colour I had declared in color.xmlwhich would be the colour of the tab line indicator. Also note that the variables above were global which I defined previously in this activity:

SlidingTabLayout mSlidingTabLayout;
ViewPager mViewPager;

6.Finally, setup the ViewPagerAdapterwhich I had called earlier. This would be responsible for changing the page depending on which tab was selected. I used the following code:

6.Finally, setup the ViewPagerAdapterwhich I had called earlier. This would be responsible for changing the page depending on which tab was selected. I used the following code:

public class ViewPagerAdapter extends FragmentPagerAdapter {

    public ViewPagerAdapter(FragmentManager fm) {
        super(fm);
    }

    @Override
    public int getCount() {
        // Returns the number of tabs
        return 3;
    }

    @Override
    public Fragment getItem(int position) {
        // Returns a new instance of the fragment
        switch (position) {
            case 0:
                return new FragmentOne();
            case 1:
                return new FragmentTwo();
            case 2:
                return new FragmentThree();
        }
        return null;
    }

    @Override
    public CharSequence getPageTitle(int position) {
        Locale l = Locale.getDefault();
        switch (position) {
            case 0:
                return getString(R.string.title_section1).toUpperCase(l);
            case 1:
                return getString(R.string.title_section2).toUpperCase(l);
            case 2:
                return getString(R.string.title_section3).toUpperCase(l);
        }
        return null;
    }
}


As I mentioned above, further details to these solutions are available on another question I answered, about using Sliding Tabs with the Toolbar.

As I mentioned above, further details to these solutions are available on another question I answered, about using Sliding Tabs with the Toolbar.