Android Fragments: Complete Guide

In Android, a Fragment is a reusable UI component that can be dynamically loaded and managed within an Activity. To use a Fragment, you first need to create a subclass of the Fragment class. Then, you can manage the Fragment’s lifecycle and interactions in the Activity using the FragmentManager.

Here are the basic steps to using Fragments:

  1. Create a Fragment class: Make a subclass that inherits from Fragment, and implement its lifecycle methods and UI layout.
public class MyFragment extends Fragment {
    
    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_layout, container, false);
        return view;
    }
}
  1. To add a Fragment in an Activity: Include a Fragment container in the layout file of the Activity, and then dynamically load and manage the Fragment in the Activity using FragmentManager.
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction transaction = fragmentManager.beginTransaction();

MyFragment myFragment = new MyFragment();
transaction.replace(R.id.fragment_container, myFragment);
transaction.commit();
  1. Interacting with Fragments: Communication can be done through the FragmentManager and instances of Fragment, such as passing data or invoking methods.
Bundle bundle = new Bundle();
bundle.putString("key", "value");
myFragment.setArguments(bundle);

// 在Fragment中获取数据
String data = getArguments().getString("key");

By following the steps above, it is possible to use Fragments in Android applications to create a flexible and modular UI interface.

bannerAds