hello worlds part 1

Upload: finder08

Post on 09-Apr-2018

231 views

Category:

Documents


0 download

TRANSCRIPT

  • 8/7/2019 Hello Worlds Part 1

    1/15

    Half Dozen Hello Worlds Part 1 Your First Android ProjectHello World is a traditional first program because it shows the very simple task of letting the user

    know you are there (or letting them know that you know that they are there). Its simple I/O to send

    a simple message. I am going to give a very brief tour of some of the ways you can communicate

    with a user in Android in this post. Half Dozen Hello Worlds will highlight some simple I/O andget you started writing your first Android programs. First lets go ahead and open Eclipse, whereyou have already setup Android, and create a new Android Project. Go to File -> New -> Project.

    Select Android Project and click next.

    Fill out the information on the next screen for your project.

    http://www.learn-android.com/2009/11/03/getting-setup-with-android/http://www.learn-android.com/2009/11/03/getting-setup-with-android/
  • 8/7/2019 Hello Worlds Part 1

    2/15

    You can put whatever you like for the project name, and application name. Note that I selected

    Android SDK 1.1. It is a good idea to select the oldest SDK which has all of the features yourprogram needs, to increase compatibility across devices. You can think of Create Activity as being

    similar to create Main Method. The name of the Activity you place here is the class that will be

    called when Android tries to run your code. Once you click Finish you should see the Project.

  • 8/7/2019 Hello Worlds Part 1

    3/15

    If you expand the project, then expand the src folder, and

    then the package you will see a Java file. This file will be named whatever you called your Activity(so mine is Hello.java). For simplicity I am going to assume you used the same settings I did when

    creating your project. If you did not just substitute your Activity name for mine. Double click onHello.java and look at the code that Eclipse has already provided you.

    packagecom.learnandroid.hellowworld;importandroid.app.Activity;importandroid.os.Bundle;publicclass Hello extends Activity { /** Called when the activity is first created. */

    @Override

    publicvoid onCreate(Bundle savedInstanceState){ super.onCreate(savedInstanceState);

    setContentView(R.layout.main); }}

    Just to give a quick overview. The package declaration just places this class in the package wespecified when we created the project. The two import statements just import the minimum

    Android libraries needed for an Activity. Since Eclipse created this as an Activity it is going to

    inherit from the Activity class, and we are overriding onCreate, which is called when an Activity iscreated. We call onCreate of the superclass. Finally, we are at the one line of code we really care

    about right now.setContentView() tells android what to display to the user. We are going to change this from thedefault so that our code looks like this:

    packagecom.learnandroid.helloworld;importandroid.app.Activity;importandroid.os.Bundle;importandroid.widget.TextView;publicclass Hello extends Activity { /** Called when the activity is first created. */

    @Override

    publicvoid onCreate(Bundle savedInstanceState){ super.onCreate(savedInstanceState);

    TextView helloText =new TextView(this);

  • 8/7/2019 Hello Worlds Part 1

    4/15

    helloText.setText("Hello World");setContentView(helloText);

    }}

    Lets briefly look at exactly what we did before moving on. TextView is an android widget that

    displays text. You can think of it as a label, something the user can read but cannot edit. We

    instantiated a new TextView. Then we called the setText method to set the text of it to HelloWorld.

    Next we used setContentView to tell Android that our TextView was what we wanted to display inthe main part of our application.

    Once your code looks like mine, go to the Run Menu and select Run In the Run As Popup selectAndroid Application. Your Android Emulator should launch. The Emulator will normally start on

    a lock screen, but as soon as you unlock the device you should see your application launch.

    Congratulations! You have built the first Hello World. This is not the preferred method forcreating an android application, however, because the contents of the View (what the user sees) is

    being generated directly from the code. Android prefers that this be separated out of the code and

    placed into an XML file. Well look at how to do this next in Part 2 of this series.

    http://www.learn-android.com/2009/11/19/half-dozen-hello-worlds-part-2/http://www.learn-android.com/2009/11/19/half-dozen-hello-worlds-part-2/
  • 8/7/2019 Hello Worlds Part 1

    5/15

    Half Dozen Hello Worlds Part 2 Using Layout XML

    This is part 2 of a multipart series that looks at some basic Android I/O using some simple HelloWorld programs. If you havent already read it you should probably start with Part 1. For this part

    we are going to create a new project with these settings.

    Thedefault Hello2.java will look very similar to the default Hello.java fromPart 1.

    packagecom.learnandroid.hellowworld;

    http://www.learn-android.com/2009/11/16/half-dozen-hello-worlds-part-1/http://www.learn-android.com/2009/11/16/half-dozen-hello-worlds-part-1/http://www.learn-android.com/2009/11/16/half-dozen-hello-worlds-part-1/http://www.learn-android.com/2009/11/16/half-dozen-hello-worlds-part-1/http://www.learn-android.com/2009/11/16/half-dozen-hello-worlds-part-1/http://www.learn-android.com/2009/11/16/half-dozen-hello-worlds-part-1/
  • 8/7/2019 Hello Worlds Part 1

    6/15

    importandroid.app.Activity;importandroid.os.Bundle;publicclass Hello2 extends Activity { /** Called when the activity is first created. */

    @Override

    publicvoid onCreate(Bundle savedInstanceState){ super.onCreate(savedInstanceState);setContentView(R.layout.main);

    }}

    This time, however, we are going to find out more about the line setContentView(R.layout.main);

    In the first example we used setContentView to render our TextView to the screen. By default,

    however, Android is designed to use XML files to setup your UI. In addition to the src folder,which holds the source code intended to be edited by the developer, there is a gen folder and a res

    folder. The gen folder holds automatically generated code. If you open this folder and expand thenamespace you should see R.java. Well come back to R.java in a moment. Before we open that

    file, lets also expand the contents of the res folder. The res folder holds resources for your androidapp. By default you should see three folders in here, drawable (which holds an android icon), layout(which contains main.xml), and values (which contains strings.xml). If you open main.xml and

    click on the main.xml tab you should see the XML that provides your activity its layout.

    We

    arent going to go into too much detail in this post on the UI XML. I will highlight, however, thatthe main node is LinearLayout which is a Layout Container that simply lines its children up in orderone after another. android:orientation indicates whether they are lined up vertically or horizontally.

    The one child node we have in LinearLayout in a TextView. This is the same control we used inPart 1, but instead of instantiating it in our code we are using the UI XML to tell Android to provide

    us with one. The other thing I want you to notice is the line android:text=@string/hello. This is

    going to set the value of our TextView. If you go back to the res folder, open values, openstrings.xml and click on the strings.xml tab you can see exactly what value we are putting into our

    TextView. In strings.xml there is a line

    Hello World, Hello2!

    so android:text=@string/hello will get this value and place it in the TextView that is displayed tothe user. Lets go ahead and change the value to our simple Hello World now.

    http://www.learn-android.com/?p=44http://www.learn-android.com/?p=44
  • 8/7/2019 Hello Worlds Part 1

    7/15

    Hello World

    Go ahead and save your change and close both strings.xml and main.xml. At this point you are

    probably wondering how Android gets the information from the XML files and uses them in yourprogram. Go back to the gen folder and open R.java and well see the answer.

    When R.Java is generated itcreates a class for each resource type (drawable, layout, and string) and variables in each classproviding access to your resources. so R.layout.main actually maps to your main.xml file via this R

    Class and the layout inner class. If you dont exactly understand what is going on here dont worry.

    Just remember that R will let you access items in your res folder so the line.

    setContentView(R.layout.main);

    tells android to use the layout in your main.xml file in res/layout. Since we edited the value instring.xml we should be able to run this program and see our Hello World displayed. Before we

    move on to part three, lets modify this program a little bit to show how to access a View element

    (such as our TextView) in our code.

    Half Dozen Hello Worlds Part 2 Using Layout XML

    In order to make our TextView accessible in our code were going to start by opening main.xml

    in /res/layout and editing it like so:

  • 8/7/2019 Hello Worlds Part 1

    8/15

    Weve removed the line

    android:text=@string/hello

    and replaced it with the lineandroid:id=@+id/label

    The @+id tells Android that we are giving the TextView an ID inside of our ApplicationNamespace. This will allow us to access it in our code. Lets open up Hello2.java in our src folder.

    packagecom.learnandroid.hellowworld;importandroid.app.Activity;importandroid.os.Bundle;importandroid.widget.TextView;publicclass Hello2 extends Activity {

    /** Called when the activity is first created. */@Override

    publicvoid onCreate(Bundle savedInstanceState){ super.onCreate(savedInstanceState);

    setContentView(R.layout.main);TextView label =(TextView) findViewById(R.id.label);label.setText("Hello World");

    }

    }

    Weve added two lines of code. The first:

    TextView label =(TextView) findViewById(R.id.label);

    uses the findViewById method to get the View, which we cast to a TextView. Notice how our

    automatically generated R class automatically provides us with the id we defined in main.xml. The

    next line:

    label.setText("Hello World");

    Simply sets the text to Hello World. If you run this application now you should see (once again)

    Hello World on your screen. That wraps up part 2. Make sure to check out Part 3of the series

    where we explore two kinds of pop-up messages available in Android.

    http://www.learn-android.com/2009/11/25/half-dozen-hello-worlds-part-3/http://www.learn-android.com/2009/11/25/half-dozen-hello-worlds-part-3/http://www.learn-android.com/2009/11/25/half-dozen-hello-worlds-part-3/
  • 8/7/2019 Hello Worlds Part 1

    9/15

    Half Dozen Hello Worlds Part 3 Using Popup Notifications

    This is part 3 of a multi-part series that looks at some basic Android I/O using simple Hello Worldprograms. At this point Ill assume you know how to make a new Android Project in Eclipse as that

    was covered in Part 1. In this part we are going to look at two types of pop-up messages that allowyou to communicate with the user outside of the normal program flow.

    ToastsImagine you are at a large dinner party. You want to make a toast to your host. You raise your

    glass a call out a toast. Half the people at the party dont notice (none of the kids at the kids tablenotice at all), but you arent worried about that as you clink glasses with the dozen people who did

    notice. The first pop-up we are going to look at is Androids Toast, which does exactly this. Itallows you to present a message to the user without any confirmation that they noticed the

    message. Build a new project using Android SDK 1.1 and update your Activity Java to look like

    this.

    packagecom.learnandroid.helloworld;importandroid.app.Activity;importandroid.os.Bundle;importandroid.view.Gravity;importandroid.widget.Toast;publicclass Hello3 extends Activity { /** Called when the activity is first created. */

    @Override publicvoid onCreate(Bundle savedInstanceState){ super.onCreate(savedInstanceState);

    setContentView(R.layout.main);

    Toast helloToast = Toast.makeText(this, "Hello World",Toast.LENGTH_LONG);

    helloToast.setGravity(Gravity.CENTER, 0, 0);helloToast.show();

    }}

    The first line of code we added to the default code generated by the project was this.

    Toast helloToast = Toast.makeText(this, Hello World, Toast.LENGTH_LONG);

    This line of code calls the Static method makeText of the Toast class. The makeText methodreturns a Toast object that will display the message you provide, in our case Hello World, for the

    duration you specify. The two available durations are Toast.LENGTH_LONG andToast.LENGTH_SHORT. Once we have our Toast object we can just call the show method to

    display it on the screen. Before displaying our toast, however, I thought I would center it on the

    screen. The setGravity method lets you tell Android where the toast should be displayed by usingone of the Gravity constants, and then specifying an x offset and y offset. Since I wanted it in the

    very center of the screen I used Gravity.Center and specified offsets of 0.

    helloToast.setGravity(Gravity.CENTER, 0, 0);

    You can see a list of available Gravity constants here. When you run this code you should see a

    small pop-up with the message Hello World appear, and then disappear automatically without anyuser interaction. On the next page well look at a pop-up that requires user interaction.

    http://www.learn-android.com/2009/11/16/half-dozen-hello-worlds-part-1/http://developer.android.com/reference/android/view/Gravity.htmlhttp://www.learn-android.com/2009/11/16/half-dozen-hello-worlds-part-1/http://developer.android.com/reference/android/view/Gravity.html
  • 8/7/2019 Hello Worlds Part 1

    10/15

    AlertsWhen I was a kid I used to love The Great Muppet Caper. I vividly remember a scene whereGonzo shouts, Stop the Presses! The editor asks him what happened and he says, I just always

    wanted to say that. If you want a pop-up that makes sure it gets attention (whether something

    important happened or not) then an Alert might be just what you need. Lets update our Java

    Activity to look like this:

    packagecom.learnandroid.helloworld;importandroid.app.Activity;importandroid.app.AlertDialog;importandroid.content.DialogInterface;importandroid.os.Bundle;publicclass Hello3 extends Activity { /** Called when the activity is first created. */

    @Override publicvoid onCreate(Bundle savedInstanceState){

    super.onCreate(savedInstanceState);setContentView(R.layout.main);

    AlertDialog helloAlert =new AlertDialog.Builder(this).create();helloAlert.setTitle("Half Dozen Hello Worlds Demo");helloAlert.setMessage("Hello World");helloAlert.setButton("Close", new DialogInterface.OnClickListener(){

    @Override publicvoid onClick(DialogInterface arg0, int arg1){} });

    helloAlert.show(); }}

    The lines weve added are:

    AlertDialog helloAlert =new AlertDialog.Builder(this).create();helloAlert.setTitle("Half Dozen Hello Worlds Demo");helloAlert.setMessage("Hello World");helloAlert.setButton("Close", new DialogInterface.OnClickListener(){

    @Override publicvoid onClick(DialogInterface arg0, int arg1){} });

    helloAlert.show();

    The AlertDialog Class makes use of the Builder Class AlertDialogBuilder. So in the first line whenwe call:

    AlertDialog helloAlert = new AlertDialog.Builder(this).create();

    We are using the Builder to return an AlertDialog object to us that is already partially setup for our

    use. The next two lines use setTitle and setMessage to set the text displayed to the user in the

    dialogs title section and body respectively. Finally, we need to have a way for the user to actuallyinteract with our alert. At minimum we should have a close button so the user can make the alert go

    away. We use setButton, passing it the text that should be displayed on the button, and an event thatallows us to perform actions when the button is clicked. By default, the dialog will be closed on a

    click event so we dont need to put any code into our event. Finally we call the show method, like

    we did with toast, to display our Hello World pop-up.

    While that technically finishes both of our Hello World pop-up programs I want to take a momentto examine the buttons on the AlertDialog

  • 8/7/2019 Hello Worlds Part 1

    11/15

    AlertDialog ButtonsIn SDK 1.1 there were three methods we used to make buttons in our AlertDialog: setButton,setButton2, and setButton3. In our example here we are only using setButton. That will give us a

    single button that is centered horizontally in the AlertDialog. If we also called setButton2 we

    would have two buttons side by side with our first button on the left and our second button on the

    right. If we include all three buttons like this:

    AlertDialog helloAlert =new AlertDialog.Builder(this).create();helloAlert.setTitle("Half Dozen Hello Worlds Demo");helloAlert.setMessage("Hello World");helloAlert.setButton("Button", new DialogInterface.OnClickListener(){

    @Override publicvoid onClick(DialogInterface arg0, int arg1){} });

    helloAlert.setButton2("Button2", new DialogInterface.OnClickListener(){@Override

    publicvoid onClick(DialogInterface arg0, int arg1){} });

    helloAlert.setButton3("Button3", new DialogInterface.OnClickListener(){@Override

    publicvoid onClick(DialogInterface arg0, int arg1){} });

    helloAlert.show();

    We would see our first button on the far left, the second on the far right, and the third in the middlelike so.

  • 8/7/2019 Hello Worlds Part 1

    12/15

  • 8/7/2019 Hello Worlds Part 1

    13/15

  • 8/7/2019 Hello Worlds Part 1

    14/15

    use Text to Speech to make your Android Device actually say Hello World.

    Half Dozen Hello Worlds Part 4 Android Text to Speech

    This is part 4 of a multi-part series that looks at some basic Android I/O using simple Hello Worldprograms. At this point Ill assume you know how to make a new Android Project in Eclipse as that

    was covered in Part 1.

    In this part we are going to look at using Androids Text to Speech capabilities to get our Androiddevice (or emulator) to actually say Hello World to the user. Text to Speech was introduced in

    Android 1.6, so when you create your new Android project make sure your minimum required SDK

    is set to Android 1.6 (or API level 4). Here is the code we are going to use to make our Androiddevice speak to us.

    packagecom.learnandroid.helloworld;importandroid.app.Activity;importandroid.os.Bundle;importandroid.speech.tts.TextToSpeech;importandroid.speech.tts.TextToSpeech.OnInitListener;publicclass Hello4 extends Activity implements OnInitListener{

    private TextToSpeech tts; staticfinalint TTS_CHECK_CODE =0;

    /** Called when the activity is first created. */@Override

    publicvoid onCreate(Bundle savedInstanceState){ super.onCreate(savedInstanceState);

    tts =new TextToSpeech(this, this); }

    @Override publicvoid onInit(int initStatus){ if(initStatus == TextToSpeech.SUCCESS) {

    tts.speak("Hello World", TextToSpeech.QUEUE_FLUSH,null); } }}

    The first thing you should notice here is the line:

    publicclass Hello4 extends Activity implements OnInitListener

    This is different from what we have seen before because it has the extra part at the end implementsOnInitListener. If you are familiar with Java you know that implements the OnInitListener

    interface. This will allow our activity to respond to the event triggered when the TextToSpeech

    engine finishes initializing. We will use the onInit method for this purpose later in our code.

    Inside the class Ive defined a class variable:

    private TextToSpeech tts;

    so it will be available to both methods in our activity. Then in the onCreate method I initialize the

    variable using the TextToSpeech class.

    http://www.learn-android.com/2009/11/16/half-dozen-hello-worlds-part-1/http://www.learn-android.com/2009/11/16/half-dozen-hello-worlds-part-1/
  • 8/7/2019 Hello Worlds Part 1

    15/15

    tts =new TextToSpeech(this, this);

    If you get an error on this line make sure you have the import android.speech.tts.TextToSpeech;statement at the top. in Eclipse you can use Ctrl + Shift + O to automatically update your import

    statements.

    The constructor for the TextToSpeech class takes two parameters. The first specifies the the

    context in which were running, and the second is the OnInitListener that should be called. Sinceour Hello4 class inherits from Activity we can use it for the context, and since it implements

    OnInitListener we can use it for the OnInitListener. Thus I simply provided the keyword this forboth parameters.

    Since we specified our class as the onInitListener to use, the class method onInit will automatically

    be called when the TextToSpeech class is initialized.

    publicvoid onInit(int initStatus){ if(initStatus == TextToSpeech.SUCCESS) {

    tts.speak("Hello World", TextToSpeech.QUEUE_FLUSH,null); } }

    This method is passed a integer indicating the status after initialization. We will compare this statuscode to the constant provided by the TextToSpeech class to indicate successful initialization

    (TextToSpeech.SUCCESS). If Initialization was successful we will call the speak method toactually have your android device speak Hello World.

    tts.speak("Hello World", TextToSpeech.QUEUE_FLUSH, null);

    This method takes three parameters. The first is the text that should be spoken. The second is the

    mode to use for speech. The mode used for speech can allow you to either speak the textimmediately (using QUEUE_FLUSH as we did here) or queue up multiple strings to be read. Since

    this is intended to be a very simple example we wont cover this functionality here. The finalparameter allows you to pass a list of additional parameters. This is also outside the scope of this

    example.

    This is the end of our tutorial on Text To Speech. Thanks for reading and be sure to check back;

    there is one more Hello World example forthcoming.