Android
 Computer >> コンピューター >  >> プログラミング >> Android

【Android】TabLayoutを使ってタブレイアウトを作成する方法を徹底解説

この記事では、Androidアプリでタブレイアウト(TabLayout)を作成する方法を、実際のサンプルコードとともに段階的に解説します。TabLayoutとViewPagerを組み合わせることで、指でスワイプしながら画面を切り替えられる、直感的なタブ型UIを簡単に実装できます。

手順1:Android Studioで新規プロジェクトを作成する

まず、Android Studioを起動し、メニューから「File」→「New Project」を選択します。必要な項目をすべて入力して、新しいプロジェクトを作成しましょう。

手順2:依存関係(Dependency)を追加する

タブレイアウトを使用するために、build.gradleファイルに以下の依存関係を追加します。

implementation 'com.android.support:design:28.0.0'

※なお、supportライブラリは現在非推奨となっています。新しいプロジェクトでは、AndroidX対応のMaterial Componentsライブラリ(com.google.android.material:material)を使用するのがおすすめです。

手順3:レイアウトファイル(activity_main.xml)を編集する

res/layout/activity_main.xmlに、以下のコードを追加します。

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
   xmlns:android="https://schemas.android.com/apk/res/android"
   xmlns:tools="https://schemas.android.com/tools"
   android:layout_width="match_parent"
   android:layout_height="match_parent"
   tools:context=".MainActivity">
   <android.support.design.widget.TabLayout
      android:id="@+id/tabLayout"
      android:layout_width="match_parent"
      android:layout_height="wrap_content"
      android:background="#1db995">
   </android.support.design.widget.TabLayout>
   <android.support.v4.view.ViewPager
      android:id="@+id/viewPager"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:layout_below="@id/tabLayout"
      android:layout_centerInParent="true"
      android:layout_marginTop="100dp"
      tools:layout_editor_absoluteX="8dp" />
</RelativeLayout>

ここでは、画面上部にTabLayoutを配置し、その下にViewPagerを配置しています。ViewPagerはタブの切り替えに連動してページをスワイプ表示するための部品です。

手順4:MainActivity.javaを実装する

src/MainActivity.javaに、以下のコードを追加します。

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.design.widget.TabLayout;
import android.support.v4.view.ViewPager;
public class MainActivity extends AppCompatActivity {
   TabLayout tabLayout;
   ViewPager viewPager;
   @Override
   protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);
      tabLayout = findViewById(R.id.tabLayout);
      viewPager = findViewById(R.id.viewPager);
      tabLayout.addTab(tabLayout.newTab().setText("Football"));
      tabLayout.addTab(tabLayout.newTab().setText("Cricket"));
      tabLayout.addTab(tabLayout.newTab().setText("NBA"));
      tabLayout.setTabGravity(TabLayout.GRAVITY_FILL);
      final MyAdapter adapter = new MyAdapter(this,getSupportFragmentManager(),
      tabLayout.getTabCount());
      viewPager.setAdapter(adapter);
      viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
      tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
         @Override
         public void onTabSelected(TabLayout.Tab tab) {
            viewPager.setCurrentItem(tab.getPosition());
         }
         @Override
         public void onTabUnselected(TabLayout.Tab tab) {
         }
         @Override
         public void onTabReselected(TabLayout.Tab tab) {
         }
      });
   }
}

このコードでは、「Football」「Cricket」「NBA」の3つのタブを追加し、タブ選択時とページスクロール時のイベントを相互に同期させています。これにより、タブをタップしても、画面をスワイプしても、両者が連動して動作します。

手順5:アダプタークラス(MyAdapter.java)を作成する

次に、Javaクラス「MyAdapter.java」を新規作成し、以下のコードを追加します。

import android.content.Context;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.app.FragmentManager;
class MyAdapter extends FragmentPagerAdapter {
   Context context;
   int totalTabs;
   public MyAdapter(Context c, FragmentManager fm, int totalTabs) {
      super(fm);
      context = c;
      this.totalTabs = totalTabs;
   }
   @Override
   public Fragment getItem(int position) {
      switch (position) {
         case 0:
            Football footballFragment = new Football();
         return footballFragment;
         case 1:
            Cricket cricketFragment = new Cricket();
         return cricketFragment;
         case 2:
            NBA nbaFragment = new NBA();
         return nbaFragment;
         default:
         return null;
      }
   }
   @Override
   public int getCount() {
      return totalTabs;
   }
}

FragmentPagerAdapterを継承したこのアダプターは、タブの位置(position)に応じて、表示するフラグメントを返す役割を担います。

手順6:フラグメントとそのレイアウトを作成する

続いて、各タブに表示するフラグメントを作成します。プロジェクトを右クリック →「New」→「Fragment」→「Blank Fragment」を選択して、空のフラグメントを生成しましょう。

a)Football.java

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class Football extends Fragment {
   public Football() {
      // Required empty public constructor
   }
   @Override
   public View onCreateView(LayoutInflater inflater, ViewGroup container,
    Bundle savedInstanceState) {
      return inflater.inflate(R.layout.fragment_football, container, false);
   }
}

fragment_football.xml

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="https://schemas.android.com/apk/res/android"
   xmlns:tools="https://schemas.android.com/tools"
   android:layout_width="match_parent"
   android:layout_height="match_parent"
   tools:context=".Football">
   <!-- TODO: Update blank fragment layout -->
   <TextView
      android:layout_width="match_parent"
      android:layout_height="match_parent"
      android:textAlignment="center"
      android:text="Football Fragment"
      android:textSize="16sp"
      android:textStyle="bold"/>
</FrameLayout>

b)Cricket.java

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class Cricket extends Fragment {
   public Cricket() {
      // Required empty public constructor
   }
   @Override
   public View onCreateView(LayoutInflater inflater, ViewGroup container,
    Bundle savedInstanceState) {
      return inflater.inflate(R.layout.fragment_cricket, container, false);
   }
}

fragment_cricket.xml

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="https://schemas.android.com/apk/res/android"
   xmlns:tools="https://schemas.android.com/tools"
   android:layout_width="match_parent"
   android:layout_height="match_parent"
   tools:context=".Cricket">
   <TextView
      android:layout_width="match_parent"
      android:layout_height="match_parent"
      android:textAlignment="center"
      android:text="Cricket Fragment"
      android:textSize="16sp"
      android:textStyle="bold"/>
</FrameLayout>

c)NBA.java

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class NBA extends Fragment {
   public NBA() {
      // Required empty public constructor
   }
   @Override
   public View onCreateView(LayoutInflater inflater, ViewGroup container,
    Bundle savedInstanceState) {
      return inflater.inflate(R.layout.fragment_nb, container, false);
   }
}

fragment_nba.xml

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="https://schemas.android.com/apk/res/android"
   xmlns:tools="https://schemas.android.com/tools"
   android:layout_width="match_parent"
   android:layout_height="match_parent"
   tools:context=".NBA">
   <!-- TODO: Update blank fragment layout -->
   <TextView
      android:layout_width="match_parent"
      android:layout_height="match_parent"
      android:textAlignment="center"
      android:text="NBA Fragment"
      android:textSize="16sp"
      android:textStyle="bold"/>
</FrameLayout>

それぞれのフラグメントには、どのタブが表示されているかがひと目でわかるように、中央揃えのテキストを配置しています。

手順7:AndroidManifest.xmlを確認・編集する

最後に、androidManifest.xmlに以下のコードを追加します。

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="https://schemas.android.com/apk/res/android"
   package="app.com.sample">
   <application
      android:allowBackup="true"
      android:icon="@mipmap/ic_launcher"
      android:label="@string/app_name"
      android:roundIcon="@mipmap/ic_launcher_round"
      android:supportsRtl="true"
      android:theme="@style/AppTheme">
      <activity android:name=".MainActivity">
         <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
         </intent-filter>
      </activity>
   </application>
</manifest>

アプリを実行して動作を確認しよう

それでは、アプリケーションを実行してみましょう。ここでは、実機のAndroidスマートフォンをパソコンに接続しているものとします。Android Studioからアプリを実行するには、プロジェクト内のアクティビティファイルをいずれか開き、ツールバーの「Run」アイコンをクリックします。デバイスの選択画面で自分のモバイル端末を選択すると、端末に以下のような画面が表示されます。

【Android】TabLayoutを使ってタブレイアウトを作成する方法を徹底解説

【Android】TabLayoutを使ってタブレイアウトを作成する方法を徹底解説 

【Android】TabLayoutを使ってタブレイアウトを作成する方法を徹底解説

タブをタップしたり、画面を左右にスワイプしたりすることで、Football・Cricket・NBAの3つの画面が滑らかに切り替われば成功です。今回の仕組みを応用すれば、ニュースアプリやSNSアプリなどでよく見られる、本格的なタブ型ナビゲーションを実装できます。

  1. 【Android】XMLファイルを使ってアニメーションを作成する方法をわかりやすく解説

    この記事では、AndroidアプリにおいてXMLファイルを使用してアニメーションを作成する方法を、実際のコード例とともに段階的に解説します。View Animation(Tween Animation)は、res/animディレクトリに配置したリソースファイルとして定義できるため、フェードインやズーム、点滅といった演出をJava側のコードをほとんど書かずに実現できるのが特徴です。 ステップ1:新規プロジェクトの作成 Android Studioを起動し、メニューから「File」⇒「New Project」を選択して新しいプロジェクトを作成します。ウィザードに従って必要な情報を入力し、プロジェク

  2. Androidのホーム画面にショートカットを作成する方法【サイト・ブックマーク・ファイル対応】

    スマホにすでにインストール済みのアプリをホーム画面に追加する方法は、多くの方がご存じでしょう。アプリドロワー(アプリ一覧)を開き、アプリアイコンを長押ししてつかみ、好きなホーム画面までドラッグするだけです。しかし、特定のフォルダやWebページ、ブックマーク一覧などへの「アプリのようなショートカット」を作りたいと思ったことはありませんか?その場合は、もう少し踏み込んだ操作が必要になります。この記事では、Androidであらゆるものへのホーム画面ショートカットを作成する方法をわかりやすくご紹介します。Webサイトへのショートカットを作成するWebサイトへのショートカット作成はとても簡単です。Chr