You have added buttons to your app's main screen, but currently the buttons do nothing. In this task, you will make your buttons respond when the user presses them.
First you will make the Toast button show a pop-up message called a toast. Next you will make the Count button update the number that is displayed in the TextView.
How to find a view by its ID.
How to add click listeners for a view.
How to set and get property values of a view from your code.
To make your life easier, you can enable auto-imports so that Android Studio automatically imports any classes that are needed by the Java code.
In Android Studio, open the settings editor by going to Settings > Editor > General.
Select Auto Imports. In the Java section, make sure Add unambiguous imports on the fly is checked.
3. Close the settings editor by pressing OK.
In this step, you will attach a Java method to the Toast button to show a toast when the user presses the button. A toast is a short message that appears briefly at the bottom of the screen.
1. Open FirstFragment.java (app > java > com.example.android.myfirstapp > FirstFragment).
This class has only two methods, onCreateView() and onViewCreated(). These methods execute when the fragment starts.
As mentioned earlier, the id for a view helps you identify that view distinctly from other views. Using the findViewByID() method, your code can find the random_button using its id, R.id.random_button.
2. Take a look at onViewCreated(). It sets up a click listener for the random_button, which was originally created as the Next button.
view.findViewById(R.id.random_button).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
NavHostFragment.findNavController(FirstFragment.this)
.navigate(R.id.action_FirstFragment_to_SecondFragment);
}
});
Here is what this code does:
Use the findViewById() method with the id of the desired view as an argument, then set a click listener on that view.
In the body of the click listener, use an action, which in this case is for navigating to another fragment, and navigate there. (You will learn about that later.)
3. Just below that click listener, add code to set up a click listener for the toast_button, which creates and displays a toast. Here is the code:
view.findViewById(R.id.toast_button).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Toast myToast = Toast.makeText(getActivity(), "Hello toast!", Toast.LENGTH_SHORT);
myToast.show();
}
});
4. Run the app and press the Toast button. Do you see the toasty message at the bottom of the screen?
5. If you want, extract the message string into a resource as you did for the button labels.
You have learned that to make a view interactive you need to set up a click listener for the view which says what to do when the view (button) is clicked on. The click listener can either:
Implement a small amount of code directly.
Call a method that defines the desired click behavior in the activity.
The method that shows the toast is very simple; it does not interact with any other views in the layout. In the next step, you add behavior to your layout to find and update other views.
Update the Count button so that when it is pressed, the number on the screen increases by 1.
In the fragment_first.xml layout file, notice the id for the TextView:
<TextView
android:id="@+id/textview_first"
In FirstFragment.java, add a click listener for the count_button below the other click listeners in onViewCreated(). Because it has a little more work to do, have it call a new method, countMe().
view.findViewById(R.id.count_button).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
countMe(view);
}
});
In the FirstFragment class, add the method countMe() that takes a single View argument. This method will be invoked when the Count button is clicked and the click listener called.
private void countMe(View view) {
}
Get the value of the showCountTextView. You will define that in the next step.
...
// Get the value of the text view
String countString = showCountTextView.getText().toString();
Convert the value to a number, and increment it.
...
// Convert value to a number and increment it
Integer count = Integer.parseInt(countString);
count++;
Display the new value in the TextView by programmatically setting the text property of the TextView.
...
// Display the new value in the text view.
showCountTextView.setText(count.toString());
Here is the whole method:
private void countMe(View view) {
// Get the value of the text view
String countString = showCountTextView.getText().toString();
// Convert value to a number and increment it
Integer count = Integer.parseInt(countString);
count++;
// Display the new value in the text view.
showCountTextView.setText(count.toString());
}
You could call findViewById() in countMe() to find showCountTextView. However, countMe() is called every time the button is clicked, and findViewById() is a relatively time consuming method to call. So it is better to find the view once and cache it.
In the FirstFragment class before any methods, add a member variable for showCountTextView of type TextView.
TextView showCountTextView;
In onCreateView(), you will call findViewById() to get the TextView that shows the count. The findViewById() method must be called on a View where the search for the requested ID should start, so assign the layout view that is currently returned to a new variable, fragmentFirstLayout, instead.
// Inflate the layout for this fragment
View fragmentFirstLayout = inflater.inflate(R.layout.fragment_first, container, false);
Call findViewById() on fragmentFirstLayout, and specify the id of the view to find, textview_first. Cache that value in showCountTextView.
...
// Get the count text view
showCountTextView = fragmentFirstLayout.findViewById(R.id.textview_first);
Return fragmentFirstLayout from onCreateView().
return fragmentFirstLayout;
Here is the whole method and the declaration of showCountTextView:
TextView showCountTextView;
@Override
public View onCreateView(
LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState
) {
binding = FragmentFirstBinding.inflate(inflater, container, false);
binding.getRoot();
// Inflate the layout for this fragment
View fragmentFirstLayout = inflater.inflate(R.layout.fragment_first, container, false);
// Get the count text view
showCountTextView = fragmentFirstLayout.findViewById(R.id.textview_first);
return fragmentFirstLayout;
}
Run your app. Press the Count button and watch the count update.