To implement a fragment-based UI in Android, start by defining a container in your activity's layout file. A FrameLayout serves as a placeholder for dynamic fragment loading:
<FrameLayout
android:id="@+id/fragment_container"
android:layout_width="match_parent"
android:layout_height="match_parent" />
In the activity's onCreate() method, manage fragment initialization through the FragmentManager:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
FragmentManager manager = getSupportFragmentManager();
Fragment existingFragment = manager.findFragmentById(R.id.fragment_container);
if (existingFragment == null) {
Fragment detailFragment = new DetailFragment();
manager.beginTransaction()
.add(R.id.fragment_container, detailFragment)
.commit();
}
}
The initialization process follows these steps:
- Acquire
FragmentManagerviagetSupportFragmentManager() - Check for existing fragment using
findFragmentById() - Create new fragment instance if none exists
- Execute fragment transaction through
beginTransaction() - Commit the transaction to apply changes
Within the fragment class, initialize data in onCreate():
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
dataModel = new DataItem();
}
Implement UI components in onCreateView():
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_detail, container, false);
titleInput = rootView.findViewById(R.id.detail_title);
titleInput.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
dataModel.setSubject(s.toString());
}
@Override
public void afterTextChanged(Editable s) {}
});
dateDisplay = rootView.findViewById(R.id.detail_date);
dateDisplay.setText(DateFormatUtils.formatDate(dataModel.getTimestamp()));
dateDisplay.setEnabled(false);
statusToggle = rootView.findViewById(R.id.detail_status);
statusToggle.setOnCheckedChangeListener((buttonView, isChecked) -> {
dataModel.setCompleted(isChecked);
});
return rootView;
}
Key considerations for fragment UI implementation:
- Always inflate layout through the provided
LayoutInflater - Access views through the inflated root view rather than directly
- Implement listeners to maintain data synchronization
- Return the fully configured view to the hosting activity
The fragment lifecycle ensures proper initialization sequence: onCreate() handles data setup, while onCreateView() manages UI component creation and configuration. This separation maintains clean architecture and proper memory management.