Android Tutorial

Software Setup and Configuration

Android Studio

File Structure

Components

Core Topics

Layout

View

Button

Intent and Intent Filters

Toast

RecyclerView

Fragments

Adapters

Other UI Component

Image Loading Libraries

Date and Time

Material Design

Bars

Working with Google Maps

Chart

Animation

Database

Advance Android

Jetpack

Architecture

App Publish

App Monetization

Introduction to Fragments | Android

Fragments represent a portion of the user interface in an Android application. Introduced in Android 3.0 (API level 11), they allow for a more flexible and modular design. Fragments can be reused across multiple activities and are especially popular for their adaptive nature, which helps build responsive UIs suitable for different screen sizes and orientations, such as phones and tablets.

Key Features of Fragments:

  • Modularity: Fragments encourage a modular design, as you can create independent units of UI and functionality that can be reused across multiple activities.

  • Adaptability: They allow for the creation of flexible UIs that can adapt based on the screen size. For instance, on a phone, a fragment might be used as a separate screen, while on a tablet, multiple fragments can be shown side by side in the same activity.

  • Fragment Lifecycle: Fragments have their own lifecycle, which is closely tied to the hosting activity's lifecycle. For example, when the activity is paused, all fragments within it are also paused.

  • Back Stack Management: Fragments can be added to the back stack, allowing the user to navigate backward through the fragment changes (similar to activity navigation).

Fragment Lifecycle:

Fragments have a series of lifecycle callback methods that help you understand and control their state:

  • onAttach(): Fragment gets associated with its hosting activity.
  • onCreate(): Fragment is being created.
  • onCreateView(): The view hierarchy associated with the fragment is instantiated.
  • onActivityCreated(): Called after the hosting activity's onCreate() method has completed.
  • onStart(): Fragment becomes visible.
  • onResume(): Fragment becomes interactive.
  • onPause(): Fragment's UI becomes partially invisible.
  • onStop(): Fragment is no longer visible.
  • onDestroyView(): View resources are released.
  • onDestroy(): Fragment is being destroyed.
  • onDetach(): Fragment is disassociated from its hosting activity.

Basic Example:

  • Define the Fragment:
class ExampleFragment : Fragment() {

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_example, container, false)
    }
}
  • Add Fragment to Activity:

There are generally two ways to add a fragment to an activity:

  • Statically: Directly in the XML layout.
<fragment
    android:id="@+id/example_fragment"
    android:name="com.example.app.ExampleFragment"
    android:layout_width="match_parent"
    android:layout_height="match_parent" />
  • Dynamically: Using FragmentTransaction in Kotlin/Java code.
val transaction = supportFragmentManager.beginTransaction()
transaction.replace(R.id.fragment_container, ExampleFragment())
transaction.addToBackStack(null)
transaction.commit()

Fragment Communication:

To allow fragments to communicate with their hosting activities or other fragments, you often use interfaces. The hosting activity implements the interface, and the fragment invokes methods on that interface, ensuring a clear separation of roles and responsibilities.

Conclusion:

Fragments provide a flexible way to design adaptable UIs and encourage reusability. With the increasing variety of Android devices, fragments are essential for building responsive applications that look and feel right across different screen sizes and orientations.

  1. What are fragments in Android and how to use them:

    Fragments are modular components in Android that represent a portion of a user interface or behavior in an activity. They allow developers to create flexible and reusable UI components. To use fragments, define a subclass of the Fragment class and embed it in an activity's layout using a <fragment> element or dynamically through the FragmentManager.

    public class MyFragment extends Fragment {
        // Fragment code here
    }
    
  2. Android fragment lifecycle explained:

    Fragments in Android have a lifecycle similar to activities. The key lifecycle methods include onCreate(), onCreateView(), onActivityCreated(), onStart(), onResume(), onPause(), onStop(), onDestroyView(), and onDestroy(). Understanding the fragment lifecycle is crucial for managing state and performing operations at specific points in the fragment's existence.

  3. Creating and managing fragments in Android app:

    To create and manage fragments, you can use the following approaches:

    • Static Fragment: Define a fragment in the XML layout file of an activity.

      <fragment
          android:id="@+id/myFragment"
          android:name="com.example.MyFragment"
          android:layout_width="match_parent"
          android:layout_height="match_parent"/>
      
    • Dynamic Fragment: Use FragmentManager to add, replace, or remove fragments dynamically in code.

      FragmentManager fragmentManager = getSupportFragmentManager();
      FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
      
      MyFragment myFragment = new MyFragment();
      fragmentTransaction.replace(R.id.fragmentContainer, myFragment);
      fragmentTransaction.commit();
      
  4. Working with fragment transactions in Android:

    Fragment transactions are essential for managing the addition, replacement, or removal of fragments dynamically. Use FragmentManager and FragmentTransaction to perform fragment transactions:

    FragmentManager fragmentManager = getSupportFragmentManager();
    FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
    
    // Add, replace, or remove fragments here
    
    fragmentTransaction.commit();
    
  5. How to communicate between fragments in Android:

    Fragment communication can be achieved through interfaces or the FragmentManager. Here's an example using an interface:

    public class MyFragment extends Fragment {
        private OnDataPassListener dataPassListener;
    
        public interface OnDataPassListener {
            void onDataPass(String data);
        }
    
        // Fragment code...
    
        public void sendDataToActivity(String data) {
            dataPassListener.onDataPass(data);
        }
    }
    

    In the hosting activity:

    public class MyActivity extends AppCompatActivity implements MyFragment.OnDataPassListener {
    
        // Activity code...
    
        @Override
        public void onDataPass(String data) {
            // Handle data passed from fragment
        }
    }
    

    Then, call sendDataToActivity() from the fragment to pass data to the hosting activity.