Creating Fragmant Classes
Create two fragment classes: ItemDetailFragment and MainContentFragment. Each fragment consists of a Java class and corresponding XML layout file.
Designing Layouts
Edit the XML layout files for each fragment. Using ConstraintLayout is recommended for flexible UI arrangements.
Creating Navigation Resource File
Create a new navigation resource file in the res directory. Define navigation paths between fragments by connecting them with directional arrows. The navigation graph specifies transition flows between screens.
Customize transition animations and set the starting fragment in the navigation designer sidebar.
Configuring Main Activity Layout
Add the NavHostFragment container to main_activity.xml. Locate NavHostFragment in the Containers section and configrue it with your navigation graph.
Implementation Code
MainContentFragment.java
public class MainContentFragment extends Fragment {
public MainContentFragment() {
// Required empty constructor
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_main_content, container, false);
}
@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
View rootView = getView();
if (rootView != null) {
Button navigationButton = rootView.findViewById(R.id.nav_button);
navigationButton.setOnClickListener(v -> {
NavController navController = Navigation.findNavController(v);
navController.navigate(R.id.action_mainContent_to_itemDetail);
});
}
}
}
ItemDetailFragment.java
public class ItemDetailFragment extends Fragment {
public ItemDetailFragment() {
// Required empty constructor
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_item_detail, container, false);
}
@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
View rootView = getView();
if (rootView != null) {
rootView.findViewById(R.id.return_button)
.setOnClickListener(Navigation.createNavigateOnClickListener(
R.id.action_itemDetail_to_mainContent));
}
}
}
MainActivity.java
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment);
NavigationUI.setupActionBarWithNavController(this, navController);
}
@Override
public boolean onSupportNavigateUp() {
NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment);
return navController.navigateUp();
}
}
This implementation uses data binding and requires appropriate XML configuration for complete functionality.