Intro

In this exercise we will show you how to display text in a TextView on Button click.

The Exercise

In this exercise we will be using only one activity. In this activity we will create one TextView and three buttons, and set them so when button one is pressed, the TextView to show the text “Button one is clicked!”, when button two is pressed “Button two is clicked!” and when button three is pressed “Button three is clicked”. We will also demonstrate how to use @string resources instead of hard-coded text. Hard-coding text attributes in layout is not recommended and should be avoided. So, we create a new project with an empty activity, as we have demonstrated in previous posts.

Then we set the layout for the activity. We will create a TextView and three buttons. Here is the xml code:

In this exercise we will be using ButterKnife library, if you are not familiar with this library you can check thisĀ post. First we will bind the TextView using ButterKnife library. In MainActivity we will create methods for the three buttons using the setText() method with getString() method and @string resources, we will set when button one is pressed the TextView will display text “Button one is clicked!”, when button two is pressed “Button two is clicked!” and when button three is pressed “Button three is clicked!”. Here is the code:

How to create a @string resource? In res folder there is a folder named values. In the values folder there is a xml file named strings.xml

In this file you create all of your hardcoded strings and you can use them via their name. This is how the xml code looks like in the project:

Now when we run the app and press the buttons we get the following result:

If you are interested you can get the whole project hereĀ https://github.com/AleksandarGulevski/ThreeButtonsExercise

Spread the love

Leave a Reply

Your email address will not be published.