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.
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;
}
}
Fragments can be integrated with ViewModels for better lifecycle management and data handling across configuration changes.
How do I avoid rehashing overhead with std::set in multithreaded code?
How do I find elements with custom comparators with std::set for embedded targets?
How do I erase elements while iterating with std::set for embedded targets?
How do I provide stable iteration order with std::unordered_map for large datasets?
How do I reserve capacity ahead of time with std::unordered_map for large datasets?
How do I erase elements while iterating with std::unordered_map in multithreaded code?
How do I provide stable iteration order with std::map for embedded targets?
How do I provide stable iteration order with std::map in multithreaded code?
How do I avoid rehashing overhead with std::map in performance-sensitive code?
How do I merge two containers efficiently with std::map for embedded targets?