Androidのフラグメントフレームワークの使用方法

Android Fragmentフレームワークを使用するには、次の手順に従います。

  1. フラグメントとして使用する、フラグメントクラスを継承したサブクラスを作成します。
  2. onCreateView()メソッド内で、フラグメントのレイアウトを作成および返します。レイアウトファイルはLayoutInflater.inflate()メソッドを呼び出してロードできます。
  3. 必要に応じてフラグメントを使用するには、通常アクティビティのレイアウトファイルで行いますが、タグを追加してフラグメントを参照します。
  4. アクティビティではFragmentManagerがフラグメントのライフサイクルを管理します。フラグメントトランザクションを開始するにはFragmentManagerのbeginTransaction()メソッドを呼び出します。
  5. 在Fragment事务中,可以通过调用add()、replace()、remove()等方法来添加、替换或移除Fragment。
  6. 最後に、Fragmentトランザクションをコミットするにはcommit()メソッドを呼び出して反映させる

フラグメントフレームワークを使用する方法を示す簡単な例を以下に示します。

まずFragmentを継承するサブクラスを作成します。例:MyFragment

public class MyFragment extends Fragment {

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_layout, container, false);
        // 进行相关的布局操作
        return view;
    }
}

次に、アクティビティのレイアウトファイルにフラグメントを参照するタグを追加します。

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <fragment
        android:id="@+id/my_fragment"
        android:name="com.example.MyFragment"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

</RelativeLayout>

最後に、Activity で Fragment のライフサイクルを管理する:

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        FragmentManager fragmentManager = getSupportFragmentManager();
        FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();

        MyFragment myFragment = new MyFragment();
        fragmentTransaction.add(R.id.my_fragment, myFragment);

        fragmentTransaction.commit();
    }
}

これによりAndroid Fragmentフレームワークを使った簡単な例が完成します。この例では、Fragmentの作成と使用方法を学ぶことができ、Fragmentのライフサイクル管理についても理解できます。

bannerAds