Lesson 6: Continuing Java Coding
INTRODUCTION
In this lesson you will be learning even more Java and going in depths with the buttons.
LESSON OBJECTIVES
By the end of this lesson, you will be able to:
1. How to add a button in Java
2. How to allow the buttons to change the TextView
3. how to set OnClickListener
LEARNING SEQUENCE
|
|
Required Reading
|
Read the following:
Introduction To Development Environment
· Eclipse
· Android
· Considerations for beginning programming.
|
Resources
|
View the following:
1. Eclipse
2. Android Development
|
Assignments
|
Last time we left off with setting the counter to whatever number you want. Now we’ll be learning buttons and changing the display
After the ‘;’ hit enter and start a new line. type out ‘add’ and hit space. This is telling the java that you will be adding to the display.
Now type out ‘=’ which means that add will be defined as whatever it is equal to. hit space again.
Type ‘(Button)’ which means that the add is connected to a button. Hit space again.
Type out ‘findViewById)R.id.bAdd);’ This tells the java that this button will be connected to the adding button. ‘findViewById’ means that it is finding the object by identification. If you remember, we set the addition button to ‘bAdd’ for button add.
Do the same for the subtraction button. Hit enter after the last piece of code and start out with ‘sub’ then type out the same piece of code.
After the subtraction button code, you’ll want to hit enter again and start to work on the display java.
Type out ‘display = (TextView) findViewById(R.id.tvDisplay);’ This is more or less the same code as the buttons. Just slightly modified so that it fits with a TextView instead of a Button.
Hit enter again and start to set the onClickListener. type ‘add.setOn’ and you’ll see the drop down menu appear. Click on the first one that comes up and it will finish the code to ‘add.setOnClickListener()’
Continue to type ‘new View.’ on the drop down menu will appear again and you’ll want to hit enter on the first one. It will type out a bunch of code under the name ‘Override’ That is ok, keep it.
Under the ‘TODO’ you’ll want to type two more lines of code.
First type out ‘counter++;’ which means that the button, when clicked, will add to the TextView display.
Under that, type out ‘display.setText(“Life Points: “ + counter);” Which adds to the display.
Move the mouse down to the end of that piece of code, where the error is, and type ‘;’. You just made your button work.
Continue to type out the subtraction button, it will be the same code.
Now the OnClickListener is something that makes the button always ‘waiting’ to be clicked. It creates an instances when clicked, and changes the TextView.
|
No comments:
Post a Comment