Skip to content

Commit

Permalink
TabLayout tabs
Browse files Browse the repository at this point in the history
Adding of TabLayout tabs to an activity which already has a ViewPager
(swipe views).

TabLayout is the new standard way to add tabs to an activity. TabLayout is
added like any other UI element in the activity's layout, and can then be
very easily integrated with the activity's ViewPager.

The TabLayout class is in the Design Support Library, which must be added to
the project dependencies in the module's build.gradle file:

dependencies {
  compile 'com.android.support:design:24.2.1'
}

To implement TabLayout tabs, the following steps are necessary:

- Make sure the project includes the Design Support Library
- Add a <TabLayout> element between the <Toolbar> and the <ViewPager>
  elements of the activity's layout
- In the activity's onCreate method, call setupWithViewPager(viewPager)
  on the TabLayout reference
- Make sure the PagerAdapter overrides the getPageTitle method (this is
  needed for setupWithViewPager to work)

That's it. The tabs in the TabLayout are automatically populated and
linked with the ViewPager by setupWithViewPager, and everything works.

References:
https://developer.android.com/reference/android/support/design/widget/TabLayout.html
  • Loading branch information
weibeld committed Oct 23, 2016
1 parent 49b11a7 commit cc9ae2f
Show file tree
Hide file tree
Showing 2 changed files with 3 additions and 5 deletions.
6 changes: 3 additions & 3 deletions app/src/main/java/org/weibeld/example/tabs/MainActivity.java
Original file line number Diff line number Diff line change
Expand Up @@ -17,9 +17,9 @@ public class MainActivity extends AppCompatActivity {

// Titles of the individual pages (displayed in tabs)
private final String[] PAGE_TITLES = new String[] {
"Page 1 very very long",
"Page 2 very very long",
"Page 3 very very long"
"Page 1",
"Page 2",
"Page 3"
};

// The fragments that are used as the individual pages
Expand Down
2 changes: 0 additions & 2 deletions app/src/main/res/layout/activity_main.xml
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="@+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
Expand All @@ -23,7 +22,6 @@
android:layout_height="wrap_content"
android:layout_width="match_parent"
android:background="?attr/colorPrimary"
app:tabMode="scrollable"
/>

<android.support.v4.view.ViewPager
Expand Down

0 comments on commit cc9ae2f

Please sign in to comment.