How to integrate Fragments with other Android components?

Integrating fragments with other Android components is essential for building a dynamic and responsive application. Fragments can be integrated into activities, used with view models, and combined with navigation components for seamless user experiences.

Example of Integrating Fragments in Activity

In this example, we will demonstrate how to add a fragment to an activity and communicate between them.

// MainActivity.java public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // Check if the fragment is already added if (savedInstanceState == null) { // Create a new instance of the fragment MyFragment myFragment = new MyFragment(); // Add the fragment to the 'fragment_container' FrameLayout getSupportFragmentManager().beginTransaction() .add(R.id.fragment_container, myFragment) .commit(); } } } // MyFragment.java public class MyFragment extends Fragment { @Nullable @Override public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_my, container, false); // Example of communication with the activity Button button = view.findViewById(R.id.button); button.setOnClickListener(v -> { if (getActivity() instanceof MainActivity) { ((MainActivity) getActivity()).onFragmentButtonClicked(); } }); return view; } }

Using ViewModels with Fragments

Fragments can be integrated with ViewModels for better lifecycle management and data handling across configuration changes.


Keywords: Android Fragments Fragment Integration Android Components ViewModel Dynamic UI Mobile Development Responsive Application