【初心者向け】Android Studioで学ぶフラグメント(Fragment)の使い方:サンプルコード付きチュートリアル
はじめに
このチュートリアルでは、Android Studioを使ってフラグメント(Fragment)を実装する方法を、実際のサンプルコードとともにステップごとに解説します。フラグメントはアクティビティの中に配置できる再利用可能なUI部品で、ボタンの操作に応じて画面の一部だけを切り替えたい場合などに非常に便利です。
本記事で作成するのは、2つのボタンをタップすると、それぞれ異なるフラグメントが表示されるシンプルなアプリです。
ステップ1:新規プロジェクトを作成する
まず、Android Studioで新しいプロジェクトを作成します。メニューから「File」⇒「New Project」を選択し、必要な項目を入力してプロジェクトを作成しましょう。
ステップ2:res/layout/activity_main.xml にコードを追加する
メインのレイアウトファイルに、以下のコードを記述します。
<?xml version = "1.0" encoding = "utf-8"?> <LinearLayout xmlns:android = "https://schemas.android.com/apk/res/android" xmlns:app = "https://schemas.android.com/apk/res-auto" xmlns:tools = "https://schemas.android.com/tools" android:layout_width = "match_parent" android:layout_height = "match_parent" tools:context = ".MainActivity" android:orientation = "vertical"> <Button android:id = "@+id/fragment1" android:layout_width = "wrap_content" android:layout_height = "wrap_content" android:layout_alignParentTop = "true" android:layout_centerHorizontal = "true" android:layout_marginTop = "27dp" android:text = "fragment1"/> <Button android:id = "@+id/fragment2" android:layout_width = "wrap_content" android:layout_height = "wrap_content" android:layout_alignParentTop = "true" android:layout_centerHorizontal = "true" android:layout_marginTop = "27dp" android:text = "fragment2"/> <LinearLayout android:id = "@+id/layout" android:layout_width = "wrap_content" android:layout_height = "wrap_content" android:orientation = "vertical"> </LinearLayout> </LinearLayout>
上記のコードでは、フラグメントを切り替えるための2つのボタン(fragment1・fragment2)と、実際にフラグメントを表示するための空のLinearLayoutを配置しています。
ステップ3:src/MainActivity.java にコードを追加する
次に、メインアクティビティに以下のコードを記述します。
package com.example.myapplication;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.RequiresApi;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
public class MainActivity extends AppCompatActivity {
@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final android.support.v4.app.Fragment first = new FirstFragment();
final android.support.v4.app.Fragment second = new SecondFragment();
findViewById(R.id.fragment1).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
android.support.v4.app.FragmentManager fm = getSupportFragmentManager();
android.support.v4.app.FragmentTransaction fragmentTransaction = fm.beginTransaction();
fragmentTransaction.replace(R.id.layout, first);
fragmentTransaction.commit();
}
});
findViewById(R.id.fragment2).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
FragmentManager fm = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fm.beginTransaction();
fragmentTransaction.replace(R.id.layout, second);
fragmentTransaction.commit();
}
});
}
}ポイントは、getSupportFragmentManager()でFragmentManagerを取得し、beginTransaction()でトランザクションを開始、replace()でコンテナ内のフラグメントを入れ替え、最後にcommit()で確定する、という一連の流れです。各ボタンのクリックリスナー内でこの処理を行い、押されたボタンに応じて表示するフラグメントを切り替えています。
ステップ4:src/FirstFragment.java にコードを追加する
package com.example.myapplication;
import android.annotation.SuppressLint;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
@SuppressLint("ValidFragment")
public class FirstFragment extends Fragment {
TextView textView;
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment, container, false);
textView = view.findViewById(R.id.text);
textView.setText("first");
return view;
}
}ステップ5:src/SecondFragment.java にコードを追加する
package com.example.myapplication;
import android.annotation.SuppressLint;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
public class SecondFragment extends Fragment {
TextView textView;
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment, container, false);
textView = view.findViewById(R.id.text);
textView.setText("Second");
return view;
}
}FirstFragmentとSecondFragmentは、どちらもFragmentクラスを継承し、onCreateView()内で共通のレイアウト(fragment.xml)をinflateしたうえで、TextViewに表示する文字列だけを変更しているのがポイントです。
ステップ6:res/layout/fragment.xml にコードを追加する
フラグメント用の共通レイアウトファイルを作成し、以下のコードを記述します。
<?xml version = "1.0" encoding = "utf-8"?> <LinearLayout xmlns:android = "https://schemas.android.com/apk/res/android" android:layout_width = "match_parent" android:gravity = "center" android:layout_height = "match_parent"> <TextView android:id = "@+id/text" android:textSize = "30sp" android:layout_width = "match_parent" android:layout_height = "match_parent" /> </LinearLayout>
アプリを実行してみよう
それでは、アプリを実行してみましょう。実機のAndroidスマートフォンをパソコンに接続していることを確認してください。Android Studioでプロジェクトのアクティビティファイルを開き、ツールバーのRunアイコンをクリックします。実行デバイスとして自分のスマートフォンを選択すると、端末に次のような初期画面が表示されます。

ここでボタンをタップすると、以下のようにフラグメントが切り替わります。


補足:AndroidXへの読み替えについて
本記事のサンプルコードは、以前よく使われていたサポートライブラリ(android.support.v4.app など)を使用しています。しかし現在のAndroid開発では、AndroidX(androidx.appcompat.app.AppCompatActivity、androidx.fragment.app.Fragment など)の使用が公式に推奨されています。既存のプロジェクトでAndroidXを利用している場合は、import文のパッケージ名を読み替えるだけで、同じロジックのままそのまま動作させることができます。
-
jQueryのclosest()メソッドの使い方を実例付きで解説
jQueryのclosest()メソッドは、選択された要素から出発してDOMツリーを上方向へ辿り、指定した条件に最初に一致する祖先要素を返すためのトラバース系メソッドです。親・子・兄弟といった関係性を利用して要素を操作したい場合に非常に便利です。 構文 closest()メソッドの基本構文は以下のとおりです。 $(selector).closest(filter) パラメータの説明 filter:どの祖先要素を対象にするかを指定するセレクター式です。要素名、クラス名、IDなどを指定できます。 条件に一致する祖先が見つかった時点で探索を終了し、その要素のみを返します。 一致する祖先が存在しない
-
Redis GEORADIUSBYMEMBERコマンドの使い方を実例付きで解説 – Redisチュートリアル
このチュートリアルでは、Redisに保存された地理空間データ(ジオスペーシャル値)の中から、特定の範囲内に含まれる要素を取得する方法を学びます。そのために使用するのが GEORADIUSBYMEMBER コマンドです。 GEORADIUSBYMEMBERコマンドとは GEORADIUSBYMEMBERコマンドは、キーに保存された地理空間値(ソート済みセット)のメンバーのうち、指定したメンバーの経度・緯度と半径の引数から算出される円形エリアの境界内にある1つ以上のメンバーを返すために使用します。このエリアは、指定したメンバーの経度・緯度を円の中心位置とし、指定した単位による半径を円の半径として計