FragmentはActivityと共に重要な機能を果たしていますが、いまいちわかりにくところがあります。最初に簡単なHello WorldをJavaコードで記述して表示させるところから始めてみましょう。
![fragment 02 - [Android] Fragment コードで記述する fragment 02 - [Android] Fragment コードで記述する](img/fragment-code-/fragment_02.jpg)
Android Studio 3.1.2
Android 8.1.0
Fragment
前回はタグ<fragment>を使って簡単にHello Worldを表示させました。
FragmentはActivityと共に重要な機能を果たしていますが、いまいちわかりにくところがあります。最初に簡単なHello World...
これと同じようになるようにコードで書いてみます。この方法は自由に、ダイナミックにFragmentを追加、削除ができるので本来の目的に沿ったやり方です。
FragmentManager
Activityが呼び出すレイアウト、activity_mainに前回使った<fragment>の代わりにFrameLayoutなどのViewGroupを使います。
例えばDefaultのConstraintLayoutにViewGroupとしてFrameLayoutを張り付けます。
activity_main.xmml
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"?> <android.support.constraint.ConstraintLayout 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" tools:context=".MainActivity"> <FrameLayout android:id="@+id/container" android:layout_width="match_parent" android:layout_height="300dp" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintLeft_toLeftOf="parent" app:layout_constraintRight_toRightOf="parent" app:layout_constraintTop_toTopOf="parent" /> </android.support.constraint.ConstraintLayout> |
次に、ActvityにFragmentを設定していきます。Fragmentの設定には一連のオペレーションであるトランザクション(フラグメントの追加、削除、置換など)を施します。
-
- FragmentManagerのインスタンス生成
- FragmentTransactionのインスタンスを取得
- インスタンスに対して張り付け方を指定する
- commit()で張り付けを実行する
実際のコードではこのようにします。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
|
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); if(savedInstanceState == null){ // ragmentManagerのインスタンス生成 FragmentManager fragmentManager = getSupportFragmentManager(); // FragmentTransactionのインスタンスを取得 FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction(); // インスタンスに対して張り付け方を指定する fragmentTransaction.replace(R.id.container, new TestFragment()); // 張り付けを実行 fragmentTransaction.commit(); } } |
savedInstanceState == null
最初に、BundleのsavedInstanceStateがnull、何もないときだけ設定をするようにします。FragmentはActivityのライフサイクル中に何度でも呼ばれることが可能なので最初だけ設定をするようにします。
|
|
if(savedInstanceState == null){ ... } |
FragmentManager:
FragmentManagerには2つの候補があります。サポートライブラリを使った方がAndroidバージョンが低いものもカバーできますので、基本的にはこちらがいいでしょう。ただし、その分ファイルサイズが大きくなります。
|
|
android.support.v4.app.FragmentManager android.app.FragmentManager |
またFragmentManagerは生成されたFragmentのインスタンスの状況を管理して、再度呼ばれると復元してくれます。
getSupportFragmentManager()からこのインスタンスを生成できます。getFragmentManager()というのがありますが、これはandroid.app.FragmentManager用なので間違えないようにしましょう。
FragmentTransaction:
追加、削除、置換などのメソッドが用意されています。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
|
add(int containerViewId, Fragment fragment) add(int containerViewId, Fragment fragment, String tag) remove(Fragment fragment) // 置き換え、remove()してadd()すること replace(int containerViewId, Fragment fragment) replace(int containerViewId, Fragment fragment, String tag) // Fragmentを非表示にする hide(Fragment fragment) // hideされたものを表示させる show(Fragment fragment) // UIからは外れるがFragmentMangerでactiveな状態として管理されている detach(Fragment fragment) // detachされたものをattachする attach(Fragment fragment) |
Ref: FragmentTransaction
Fragmentのレイアウトとクラスは前回と同様です。
FragmentはActivityと共に重要な機能を果たしていますが、いまいちわかりにくところがあります。最初に簡単なHello World...
サンプルコード
以上をまとめて、分かりやすいように背景色を設定してみます。
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
|
package com.example.testfragmentcode; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentTransaction; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); if(savedInstanceState == null){ // ragmentManagerのインスタンス生成 FragmentManager fragmentManager = getSupportFragmentManager(); // FragmentTransactionのインスタンスを取得 FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction(); // インスタンスに対して張り付け方を指定する fragmentTransaction.replace(R.id.container, new TestFragment()); // 張り付けを実行 fragmentTransaction.commit(); } } } |
MainActivityで呼んでいるレイアウト
activity_main.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"?> <android.support.constraint.ConstraintLayout 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:background="#dfe" android:padding="10dp" tools:context=".MainActivity"> <FrameLayout android:id="@+id/container" android:layout_width="match_parent" android:layout_height="300dp" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintLeft_toLeftOf="parent" app:layout_constraintRight_toRightOf="parent" app:layout_constraintTop_toTopOf="parent" /> </android.support.constraint.ConstraintLayout> |
Fragmentのクラスです。
TestFragment.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
|
import android.support.v4.app.Fragment; import android.os.Bundle; import android.support.annotation.NonNull; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; public class TestFragment extends Fragment { @Override public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { return inflater.inflate(R.layout.fragment_main, container, false); } } |
Fragmentが呼んでいるレイアウト
fragment_main.xml
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
|
<?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:background="#ddd" android:orientation="vertical" android:gravity="center" > <TextView android:text="@string/hello_world" android:layout_width="wrap_content" android:textSize="20sp" android:textColor="#00f" android:layout_height="wrap_content"/> </LinearLayout> |
リソース
strings.xml
|
|
<resources> ... <string name="hello_world">Hello World</string> </resources> |
これで実行させてみるとこのようになります。
![fragment 02 - [Android] Fragment コードで記述する fragment 02 - [Android] Fragment コードで記述する](img/fragment-code-/fragment_02.jpg)
関連ページ:
Ref:
フラグメント | Android Developers