Step 6: Implementing the 2nd Fragment
In this section you will learn how to pass information to the 2nd fragment by using the Random button to display a random number between 0 and the current count on the 2nd screen.
Before you begin add android:fillViewport="true" underneath <androidx.core.widget.NestedScrollView
just like in fragment_first.xml.
Part 1: Add a TextView for the Random Number
Open fragment_second.xml (app > res > layout > fragment_second.xml) and switch to Design View.
2. Delete the textview that is already in place. At this point you can go to strings.xml and delete the string resource labeled lorem_ipsum
3. Add another TextView and place it near the middle of the screen. This TextView will be used to display a random number between 0 and the count from the first Fragment.
4. Set the id of this new TextView to textview_random. This could either be by changing the xml code to @+id/textview_random or using the attributes panel.
5. Constrain the top edge of the new TextView to the bottom of the Previous button, the left side to the left side of the screen, the right edge to the right of the screen, and the bottom to the bottom of the screen.
6. Set both width and height to wrap_content.
7.Edit the textColor, textsize, and textStyle however you want.
8. Set the text to "Random" as a placeholder until the random number generated.
9. Set the layout_constraintVertical_bias to 0.45
app:layout_constraintHorizontal_bias=".45"
Constraining the button using vertical bias instead of using margins to ensure the layout looks good across screens of all different sizes.
10. Open nav_graph.xml. Go to the Layout Editor in Design view appears. It shows the 2 fragments with arrows between them. If the SecondFragment appears before the FirstFragment, drag the FirstFragment to the left of the SecondFragment.
Step 2: Enable SafeArgs
In build.gradle.kts(myFirstApp) add the following code:
buildscript {
dependencies {
val nav_version = "2.7.6"
classpath("androidx.navigation:navigation-safe-args-gradle-plugin:2.7.6")
}
}
2. Do the same for build.gradle.kts(:app) for the following code:
buildscript {
repositories {
google()
}
dependencies {
val nav_version = "2.5.3"
classpath("androidx.navigation:navigation-safe-args-gradle-plugin:$nav_version")
}
}
3. Also in this file add id("androidx.navigation.safeargs") inside of the plugins.
3. A message about Gradle files being changed should pop up. Select Sync Now on the right side.
4. Choose Build > Make Project. This should rebuild everything and allow FirstFragmentDirections to be found.
Step 3: Create the Argument for the Navigation Action.
Click on FirstFragment in the Navigation graph found in nav_graph.xml.
2. In the Attributes panel find the Action section. Click on the SecondFragment and look at the Attributes panel.
3. In the Arguments section select the +
4. In the Add Argument dialog, enter myArg for the name and set the type to Integer. Click Add.
Step 4: Send the Count to the Second Fragment
Open FirstFragment.java(app > java > com.example.myfirstapp>FirstFragment)
2. Find the method onViewCreated(); find the following code view.findViewById(R.id.random_button).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
3. Replace the code with the following code to find the count textview.
int currentCount = Integer.parseInt(showCountTextView.getText().toString());
4. Create an action with the new variable, currentCount as the argument to actionFirstFragmentToSecondFragment():
NavDirections actions = FirstFragmentDirections.actionFirstFragmentToSecondFragment();
5. Add a line to find the nav controller and navigate with the action that we just created:
NavHostFragment.findNavController(FirstFragment.this).navigate(actions);
6. The new whole method should look like the following:
view.findViewById(R.id.random_button).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
int currentCount = Integer.parseInt(showCountTextView.getText().toString());
FirstFragmentDirections.ActionFirstFragmentToSecondFragment action = FirstFragmentDirections.actionFirstFragmentToSecondFragment(currentCount);
NavHostFragment.findNavController(FirstFragment.this).navigate(action);
}
});
Step 5: Update the SecondFragment to Display a Random Number
1. In the onViewCreated() method, right below the line that starts with super, add code to get the current count.:
Integer count = SecondFragmentArgs.fromBundle(getArguments()).getMyArg();
3. Compute a random number between 0 and the count:
Random random = new java.util.Random();
Integer randomNumber = 0;
if (count > 0 ) {
randomNumber = random.nextInt(count + 1);
}
4. Convert the random number into string and set it as the text for texview_random.
TextView randomView = view.getRootView().findViewById(R.id.textview_random);
randomView.setText(randomNumber.toString());
5. The whole method should look like the following:
public void onViewCreated(@NonNull View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
Integer count = SecondFragmentArgs.fromBundle(getArguments()).getMyArg();
Random random = new java.util.Random();
Integer randomNumber = 0;
if (count > 0 ) {
randomNumber = random.nextInt(count + 1);
}
TextView randomView = view.getRootView().findViewById(R.id.textview_random);
randomView.setText(randomNumber.toString());
5. Run the app and make sure everything works.
Congrats you just made your very first app!
Now build on from this and make changes to make your app your very own.