Fragments
Fragments
Android application:
---
CIVEFragment.java
package com.example.myapp;
import android.os.Bundle;
import androidx.fragment.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class CIVEFragment extends Fragment {
public CIVEFragment() {
@Override
Bundle savedInstanceState) {
COBEFragment.java
package com.example.myapp;
import android.os.Bundle;
import androidx.fragment.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class COBEFragment extends Fragment {
public COBEFragment() {
@Override
Bundle savedInstanceState) {
COEDFragment.java
package com.example.myapp;
import android.os.Bundle;
import androidx.fragment.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
@Override
Bundle savedInstanceState) {
---
Create corresponding layout files for each fragment in the res/layout folder.
fragment_cive.xml
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="CIVE Fragment"
android:layout_gravity="center"
android:textSize="20sp" />
</FrameLayout>
fragment_cobe.xml
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="COBE Fragment"
android:layout_gravity="center"
android:textSize="20sp" />
</FrameLayout>
fragment_coed.xml
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="COED Fragment"
android:layout_gravity="center"
android:textSize="20sp" />
</FrameLayout>
---
In your activity, you can add the fragments programmatically or using a FragmentTransaction.
MainActivity.java
package com.example.myapp;
import android.os.Bundle;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
@Override
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
replaceFragment(new CIVEFragment());
fragmentManager.beginTransaction()
.replace(R.id.fragment_container, fragment)
.commit();
}
activity_main.xml
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/fragment_container"
android:layout_width="match_parent"
android:layout_height="match_parent" />
---
You can use buttons or tabs to navigate between fragments using FragmentTransaction.