ViewPager2で複数のFragment画面をスワイプで次々とスライドショーのように表示できますが、Tabを画面上につけて、タブをタップすることで目的のページに跳ぶようにすることもできます
![[Android] ViewPager2 でTabLayoutでタブ付きスワイプビューの作成 1x1.trans - [Android] ViewPager2 でTabLayoutでタブ付きスワイプビューの作成](https://akira-watson.com/wp-content/themes/simplicity2/images/1x1.trans.gif)
2021.2.1
TabLayout
こちらで使ったViewPager2にTabを付けてみたいと思います
 
以下のようにスワイプでページが変わりTabでどのページかわかるようにできます
また、この例ではインジケータがTabの下にあり分かりにくいためTabの背景とテキスト色をかえたり、インジケータをカスタマイズしてみます
| ![[Android] ViewPager2 でTabLayoutでタブ付きスワイプビューの作成 1x1.trans - [Android] ViewPager2 でTabLayoutでタブ付きスワイプビューの作成](https://akira-watson.com/wp-content/themes/simplicity2/images/1x1.trans.gif) | ![[Android] ViewPager2 でTabLayoutでタブ付きスワイプビューの作成 1x1.trans - [Android] ViewPager2 でTabLayoutでタブ付きスワイプビューの作成](https://akira-watson.com/wp-content/themes/simplicity2/images/1x1.trans.gif) | ![[Android] ViewPager2 でTabLayoutでタブ付きスワイプビューの作成 1x1.trans - [Android] ViewPager2 でTabLayoutでタブ付きスワイプビューの作成](https://akira-watson.com/wp-content/themes/simplicity2/images/1x1.trans.gif) | 
TabLayout を使用してタブを追加
<TabLayout>要素を <ViewPager2>要素の上に追加
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"     android:layout_width="match_parent"     android:layout_height="match_parent"     android:orientation="vertical">     <com.google.android.material.tabs.TabLayout         android:id="@+id/tab_layout"         android:layout_width="match_parent"         android:layout_height="wrap_content" />     <androidx.viewpager2.widget.ViewPager2         android:id="@+id/pager"         android:layout_width="match_parent"         android:layout_height="0dp"         android:layout_weight="1" /> </LinearLayout> | 
TabLayoutMediator を作成し TabLayout を ViewPager2 にリンクしアタッチ
| 1 2 3 4 5 6 7 8 9 10 | @Override protected void onCreate(Bundle savedInstanceState) {     super.onCreate(savedInstanceState);     setContentView(R.layout.activity_screen_slide);     ...     TabLayout tabLayout = findViewById(R.id.tab_layout);     new TabLayoutMediator(tabLayout, viewPager,             (tab, position) -> tab.setText("TAB " + (position + 1))     ).attach(); } | 
viewpager2のライブラリをbuild.gradleに追加しておきます
| 1 2 3 4 5 | ... dependencies {     implementation 'androidx.viewpager2:viewpager2:1.1.0-beta01'     ... } | 
サンプルコード
まとめてみると
MainActivity.java
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 | //package your.package.name; import androidx.annotation.NonNull; import androidx.fragment.app.Fragment; import androidx.fragment.app.FragmentActivity; import androidx.viewpager2.adapter.FragmentStateAdapter; import androidx.viewpager2.widget.ViewPager2; import android.os.Bundle; import com.google.android.material.tabs.TabLayout; import com.google.android.material.tabs.TabLayoutMediator; import java.util.ArrayList; public class MainActivity extends FragmentActivity {     // The pager widget, which handles animation and allows swiping horizontally     // to access previous and next wizard steps.     private ViewPager2 viewPager;     private static final String[] flowers = {         "oze_trail2", "animal_trail2", "rainbow_waterfall2"     };     private final ArrayList<Integer> flowerList = new ArrayList<>();     @Override     protected void onCreate(Bundle savedInstanceState) {         super.onCreate(savedInstanceState);         setContentView(R.layout.activity_screen_slide);         // Instantiate a ViewPager2 and a PagerAdapter.         viewPager = findViewById(R.id.pager);         // for-each member名をR.drawable.名前としてintに変換してarrayに登録         for (String member: flowers){             int imageId = getResources().getIdentifier(                     member,"drawable", getPackageName());             flowerList.add(imageId);         }         // The pager adapter, which provides the pages to the view pager widget.         FragmentStateAdapter pagerAdapter = new ScreenSlidePagerAdapter(this, flowerList);         viewPager.setAdapter(pagerAdapter);         TabLayout tabLayout = findViewById(R.id.tab_layout);         new TabLayoutMediator(tabLayout, viewPager,                 (tab, position) -> tab.setText("TAB " + (position + 1))         ).attach();     }     @Override     public void onBackPressed() {         if (viewPager.getCurrentItem() == 0) {             // If the user is currently looking at the first step,             // allow the system to handle the Back button.             // This calls finish() on this activity and pops the back stack.             super.onBackPressed();         } else {             // Otherwise, select the previous step.             viewPager.setCurrentItem(viewPager.getCurrentItem() - 1);         }     }     // A simple pager adapter that represents 5 ScreenSlidePageFragment     // objects, in sequence.     private static class ScreenSlidePagerAdapter extends FragmentStateAdapter {         ArrayList<Integer> picture;         public ScreenSlidePagerAdapter(                 FragmentActivity fa, ArrayList<Integer> flowerList) {             super(fa);             picture = flowerList;         }         @NonNull         @Override         public Fragment createFragment(int position) {             Fragment fagment =new ScreenSlidePageFragment();             Bundle bundle = new Bundle();             bundle.putInt("Page", position);             bundle.putIntegerArrayList("Photo", picture);             fagment.setArguments(bundle);             return fagment;         }         @Override         public int getItemCount() {             return picture.size();         }     } } | 
ScreenSlidePageFragment.java
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 | //package your.package.name; import android.graphics.BitmapFactory; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import androidx.annotation.NonNull; import androidx.fragment.app.Fragment; import java.util.ArrayList; public class ScreenSlidePageFragment extends Fragment {     @Override     public View onCreateView(LayoutInflater inflater,                              ViewGroup container,                              Bundle savedInstanceState) {         return  inflater.inflate(                 R.layout.fragment_screen_slide_page, container, false);     }     @Override     public void onViewCreated(@NonNull View view, Bundle savedInstanceState) {         super.onViewCreated(view, savedInstanceState);         Bundle args = getArguments();         assert args != null;         int position = args.getInt("Page");         ArrayList<Integer> image = args.getIntegerArrayList("Photo");         ImageView imageView = view.findViewById(R.id.image_view);         imageView.setImageBitmap(                 BitmapFactory.decodeResource(this.getResources(), image.get(position)));     } } | 
activity_Screen_slide.xml
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | <?xml version="1.0" encoding="utf-8"?> <LinearLayout     xmlns:android="http://schemas.android.com/apk/res/android"     android:layout_width="match_parent"     android:layout_height="match_parent"     android:orientation="vertical"     xmlns:app="http://schemas.android.com/apk/res-auto">     <com.google.android.material.tabs.TabLayout         android:id="@+id/tab_layout"         android:layout_width="match_parent"         android:layout_height="wrap_content"/>     <androidx.viewpager2.widget.ViewPager2         android:id="@+id/pager"         android:layout_width="match_parent"         android:layout_height="0dp"         android:layout_weight="1" /> </LinearLayout> | 
fragment_screen_slide_page.xml
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | <?xml version="1.0" encoding="utf-8"?> <LinearLayout     xmlns:android="http://schemas.android.com/apk/res/android"     xmlns:app="http://schemas.android.com/apk/res-auto"     xmlns:tools="http://schemas.android.com/tools"     android:layout_width="match_parent"     android:layout_height="match_parent"     android:orientation="vertical"     android:background="#888"     tools:context=".MainActivity">     <ImageView         android:id="@+id/image_view"         android:layout_width="match_parent"         android:layout_height="match_parent"         android:scaleType="centerCrop"         android:contentDescription="@string/description"/> </LinearLayout> | 
strings.xml
| 1 2 3 4 | <resources>     <string name="app_name">YourAppName</string>     <string name="description">folwer</string> </resources> | 
build.gradle
| 1 2 3 4 5 | ... dependencies {     implementation 'androidx.viewpager2:viewpager2:1.1.0-beta01'     ... } | 
Tabの背景とテキスト色を変更
Tabを付けたのですが、どこを選択しているのが分かりにくいため、
選択中のタブの背景とテキスト色を変えて分かりやすくしてみましょう
Tabが選択しているケースでの背景を設定するtab_selector.xmlを作成
選択しているときのテキスト色を白にその他は黒に設定
activity_Screen_slide.xml
| 1 2 3 4 5 6 7 8 9 | ... <com.google.android.material.tabs.TabLayout     android:id="@+id/tab_layout"     android:layout_width="match_parent"     android:layout_height="wrap_content"     app:tabBackground="@drawable/tab_selector"     app:tabTextColor="@color/black"     app:tabSelectedTextColor="@color/white"/> ... | 
\res\drawable 以下に配置
tab_selector.xml
| 1 2 3 4 5 6 7 | <?xml version="1.0" encoding="utf-8"?> <selector xmlns:android="http://schemas.android.com/apk/res/android">     <item android:drawable="@color/purple_200"         android:textColor="@color/white"         android:state_selected="true"/>     <item android:drawable="@android:color/transparent"/> </selector> | 
デフォルトではTabの下線が入るだけなので見にくかったのですが、背景色が変わるとそれなりに目立つようにできました
![[Android] ViewPager2 でTabLayoutでタブ付きスワイプビューの作成 1x1.trans - [Android] ViewPager2 でTabLayoutでタブ付きスワイプビューの作成](https://akira-watson.com/wp-content/themes/simplicity2/images/1x1.trans.gif)
Indicatorの変更
前のselectorを使う方法は、shapeと組み合わせてカスタマイズを発展させられますが
もっと簡単なものでよければ Indicatorを変更することでも可能です
例えばTabの背景色が濃いですが
app:tabIndicatorGravity=”stretch”
app:tabSelectedTextColor=”@color/white
を追加すると選択しているTabが分かりやすくなります
![[Android] ViewPager2 でTabLayoutでタブ付きスワイプビューの作成 1x1.trans - [Android] ViewPager2 でTabLayoutでタブ付きスワイプビューの作成](https://akira-watson.com/wp-content/themes/simplicity2/images/1x1.trans.gif)
| 1 2 3 4 5 6 | <com.google.android.material.tabs.TabLayout     android:id="@+id/tab_layout"     android:layout_width="match_parent"     android:layout_height="wrap_content"     app:tabIndicatorGravity="stretch"     app:tabSelectedTextColor="@color/white"/> | 
また、Indicatorの色と選択されたテキスト色を変えるとそれなりになります
app:tabIndicatorColor=”#ff0000″
app:tabSelectedTextColor=”#ff0000″
![[Android] ViewPager2 でTabLayoutでタブ付きスワイプビューの作成 1x1.trans - [Android] ViewPager2 でTabLayoutでタブ付きスワイプビューの作成](https://akira-watson.com/wp-content/themes/simplicity2/images/1x1.trans.gif)
| 1 2 3 4 5 6 | <com.google.android.material.tabs.TabLayout     android:id="@+id/tab_layout"     android:layout_width="match_parent"     android:layout_height="wrap_content"     app:tabIndicatorColor="#ff0000"     app:tabSelectedTextColor="#ff0000"/> | 
 
 
 
References:
ViewPager2 を使用してタブ付きスワイプビューを作成する
ViewPager2 を使用してフラグメント間をスライドする
ViewPager2
![[Android] ViewPager2 でTabLayoutでタブ付きスワイプビューの作成 as2021 vpager 00b 100x100 - [Android] ViewPager2 でTabLayoutでタブ付きスワイプビューの作成](https://akira-watson.com/wp-content/uploads/2022/08/as2021_vpager_00b-100x100.jpg)
