In this tutorial I am going to discuss about fragments in android application.

Fragment is just a kind of sub-activity which is used to build a multi-pane UI and reuse a fragment in multiple activities. Fragments has their own life-cycle, receives its own input events, and which you can add or remove while the activity is running (sort of like a “sub activity” that you can reuse in different activities).

Dynamic Fragment

The fragment life-cycle in android is just like the life-cycle of an activity.

Fragments are of two types :

  1. Static Fragment
  2. Dynamic Fragment

In this tutorial I am just going to discuss you about dynamic fragment.

1. Create a New Project :

Create a new project in Android Studio from File ⇒ New Project and select Empty Activity from templates to add Fragments to your app .

2. Add Frame layout to your activity_main.xml or main layout

Add a Frame layout to your activity where the fragment is inserted at run time.

<FrameLayout
       android:id="@+id/fragment"
       android:layout_width="match_parent"
       android:layout_height="match_parent">
  </FrameLayout>

Now open res -> layout -> activity_main.xml  file and just implement the following xml code

<?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:orientation="vertical" >
    <Button
        android:id="@+id/btn"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Btn"
        android:layout_gravity="center_horizontal"
        android:gravity="center_horizontal"/>
    <FrameLayout
        android:id="@+id/fragment"
        android:layout_width="match_parent"
        android:layout_height="match_parent">
    </FrameLayout>

</LinearLayout>

3. Create a Layout Resource file :

Now create a Layout Resource file and Add a fragment view named it as dynamicfragment.xml to implement dynamic fragment in android .

<?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="100dp"
    android:orientation="vertical"
    android:background="@color/colorPrimary">

    <TextView
        android:id="@+id/tv"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textColor="#fff"
        android:layout_gravity="center_horizontal"
        android:text="TestView" />

    <Button
        android:id="@+id/btn"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:text="Test Button" />

</LinearLayout>

4. Now create a fragment class :

Create a fragment and extend the fragment class, then override onCreateView methods to insert your app logic or just add following code .

package com.technxtcodelabs;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.ViewGroup;

public class DynamicFragment extends Fragment {
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.dynamicfragment, container, false);
    }
     @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        // handle your fragment events here
        TextView txtView = (TextView)view.findViewById(R.id.tv);
        Button btn = (Button)view.findViewById(R.id.btn);
        b1.setOnClickListener(new View.OnClickListener() {
         @Override
         public void onClick(View v) {
            Toast.makeText(MainActivity.this,"YOUR MESSAGE",Toast.LENGTH_LONG).show();
         }
      });

    }
}

5. Now open your MainActivity.java and add following code :

Here we use the FragmentManager to create a FragmentTransaction which allows us to add fragments dynamically to the frame layout at runtime.

// Create an object of your Fragment
DynamicFragment frg = new DynamicFragment();
// Create an object of FragmentManager
FragmentManager fm = this.getSupportFragmentManager();
// Begin the transaction
FragmentTransaction ft = fm.beginTransaction();
// Replace the container with the new fragment
ft.replace(R.id.fragment, frg);
ft.commit();

Now open your MainActivity.java and add following code :

package com.technxtcodelabs;
 
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
 
public class MainActivity extends AppCompatActivity {
    Button btn;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        btn = findViewById(R.id.btn);
        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // Create an object of your Fragment
                DynamicFragment b = new DynamicFragment();
                // Create an object of FragmentManager
                FragmentManager fm = getSupportFragmentManager();
                // Begin the transaction
                FragmentTransaction ft = fm.beginTransaction();
                // Replace the container with the new fragment
                ft.replace(R.id.fragment,b);
                ft.commit();
            }
        });

    }  
}

Now run the project/app to test fragments in android app through android device or any Emulator .

%d bloggers like this: