Showing Toast on Button Click

In this tutorial, we will show a toast on button click. Toasts are short messages fades in and out on below screen.

 

Open android studio and start a new project. If you don’t know how, you can follow this tutorial. First of all open your res/values/strings.xml file and add a string item named ‘button_text’ (name is up to you).

 

Then open your res/layout/activity_main.xml , write below code in text mode.

With above code,we just declare how our application screen looks. It has a button on center vertically and horizontally. You can observe with design mode.

 

Then open java/package_name/MainActivity.java file.

Note
We better explain some about Activities. You can assume every single screen is an activity on application. This is not true every time especially when we work with fragments but for now it is enough. Activities have a lifecycles. When activities begin,pause,destroy, some methods are called. At the begining of these tutorial, you need to know onCreate method. onCreate method can be assumed as main function of a java application. So activity starts with onCreate method. You can find your views and play some features of them on onCreate method. For more read this.

Below code sets layout of activity (screen)

So our MainActivity should be like below

Run application on simulator or real device, you can see activity_main.xml layout places on the application screen.

 

Note

In res/layout/activity_main.xml , do not forget that we set an id to button. We will use it next step.

      android:id="@+id/id_of_button"

Bind button widget of layout with java object. You can do it with findViewById method. This method takes an id as a parameter and find layout widget with this id and assign it to java object.

 

MainActivity.java should be like below

 

We have Button object right now, we need click listener to create an event

 

Add another string item named ‘toast_text’ to res/values/strings.xml

 

This code part shows a toast with text on second parameter. First parameter tells which context toast should be shown. Last parameter is time length.

 

We want to show toast when we click button.

 

Our MainActivity’s final state should be like below

 

So,everything is ready. Run application and click button, see toast message.

download_source_icon Download Source Code

If you don’t know how to open an existing Android Studio Project, follow this tutorial.

 

Bir Cevap Yazın