Sobes.tech
Junior — Middle

How to implement and integrate a Fragment into your application?

sobes.tech AI

Answer from AI

To implement a Fragment in Android:

  1. Create a class that extends Fragment and define the UI in onCreateView.
  2. Add the Fragment to an Activity via XML layout or programmatically using FragmentManager.

Example of creating a simple Fragment and adding it to an Activity programmatically:

public class MyFragment extends Fragment {
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_layout, container, false);
    }
}

// In the Activity
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction transaction = fragmentManager.beginTransaction();
transaction.replace(R.id.fragment_container, new MyFragment());
transaction.commit();

This approach allows for dynamic UI management and reusing components in different parts of the application.

How to implement and integrate a Fragment into your… - sobes.tech