Adding screens to an Android application is pretty straightforward. Coming from a web-centric .NET shop however, it took me a bit before I realized exactly how it was done. In this post I’ll be showing a bare bones way of adding screens to an Android app, along with some bare bones button navigation between the screens.

As usual, I’m assuming that you have your environment set up for Android development in Eclipse. Create a new Android project to start.

Activities

Screens in Android are defined (most of the time) in layout files. They are a part of an activity, one of the core components of an Android application. In addition to a layout, an activity also contains code that defines its behavior. You can see what activities your application contains by double clicking on the AndroidManifest.xml file and reviewing the Application Nodes section on the Application tab.

activitiesInManifest

From a bare bones perspective, to add a screen we must add an activity. Each activity must have a matching class file however, so we’ll add those first. Right click on the src node and click New –> Class.

newClass

Name this first new class screen1, and set the superclass to android.app.Activity. Ignore the warnings, we’re not going for style right now.

newActivityClass

Clicking on finish produces some truly bare bones code which we will flesh out below.

package com.screenssample;

import android.app.Activity;

public class screen1 extends Activity {

}

Now we need to add the actual activity that will use this new code. Returning to the Application tab of the Android manifest file, we click on Add in the Application Nodes section.

addActivity

We make sure to add the new element at the top level, in Application, and select Activity.

addActivity2

Then we name our activity the same as the backing class file we created above, screen1.

namedActivity

And that’s our first activity. Go ahead add a second activity named screen2 following the steps above, along with its backing code file.

Layouts

Before we can do anything else in any activity’s class, we need to define the associated layout for our new screen. Our layouts are contained in the res –> layout node in the Package Explorer.

layoutLocation

Right now we have one layout file, main.xml. This layout is loaded on application start up, as we can see by the code in main.java.

package com.screenssample;

import android.app.Activity;
import android.os.Bundle;

public class main extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
    }
}

The important line is the call to setContentView. We are passing R.layout.main to that method, which maps onto the layout defined in main.xml.

Adding Layouts

We will need to add two new layouts, one for each activity we added above. Each will have a button for navigation, and we will go from main to screen1 to screen2, back to main. So first we right click on the layout node pictured above and select New –> Android XML File.

newAndroidXmlFile

Enter the name of the new layout file (it has to be a valid filename) and make sure you don’t use uppercase characters. Yes, that’s right – I camel-cased the name of the layout file first and lost five minutes of my life to the fact that Android doesn’t want uppercase characters in layout files. After adding our new layout files, our layout folder looks like below.

screensAdded

Now we need navigation buttons on each of our screens. Double-click screen1, bringing up the basic screen designer in Eclipse.

basicScreenDesigner

There are a few ways you can add a button to this layout. We’re sticking with the mouse-driven way for now. Click and drag a TextView selection from the Views pane onto the layout surface, and then do the same with a Button selection.

buttonAdded

I detest default UI element ids (at least for buttons), so let’s change our button’s id to something more representative of what it’s doing, say nextScreen. We’ll change the button text as well. We will also change the text in the TextView to indicate what screen we’re on. As usual, there is more than one way to do this. We are going to use the Properties pane below the layout surface. Find the Id property, and change it to read @+id/nextScreen1. Then find the Text property and change it to Next screen.

idPropertyChanged

textPropertyChanged

Do the same for the main and screen2 screens, setting their id properties to nextScreenMain and nextScreen2 respectively. That finishes up our layout – now we have to tell our app to do something when the buttons are clicked.

Adding Button Handlers

Android provides a rich event-based system for controlling application UIs. We will be handling the button click events on each of our screens, bringing up the next activity in the chain when we click. Open up the main.java file, and below the setContentView method call start typing the below.

needAnImport

This was a pretty neat feature when I saw it pop up in the IDE. I’m used to Visual Studio, and the Intellisense there doesn’t seem quite as polished as what I’ve seen so far in Eclipse. Visual Studio 2010 does seem to equalize things some however. Either way, we see here that we need to import an additional package, namely android.widget. Do so, and enter the code below.

public class main extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        Button mainNext = (Button) findViewById(R.id.nextScreenMain);
        mainNext.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
                Intent i = new Intent();
                i.setClassName("com.screenssample", "com.screenssample.screen1");
                startActivity(i);
            }
        });

    }
}

The fun starts on line 8, where we are creating a reference to our button on the main screen. After that, on line 9 we are creating an anonymous method that will handle button clicks. Inside of our event handler we are spinning up our “screen1” activity by creating an Intent object with the proper class name. You can run the app at this point to test it out.

After that, finish out the example by adding similar code to the other two screens’ onCreate method, as shown below.

public class screen1 extends Activity {
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.screen1);

        Button mainNext = (Button) findViewById(R.id.nextScreen1);
        mainNext.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
                Intent i = new Intent();
                i.setClassName("com.screenssample", "com.screenssample.screen2");
                startActivity(i);
            }
        });

    }
}

public class screen2 extends Activity {
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.screen2);

        Button mainNext = (Button) findViewById(R.id.nextScreen2);
        mainNext.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
                Intent i = new Intent();
                i.setClassName("com.screenssample", "com.screenssample.main");
                startActivity(i);
            }
        });

    }
}

And there you have it – a basic Android application with three screens and (very) bare bones navigation. In future posts I’ll present more of a best practices approach on how to handle different screens (activities) within an Android application, as well as ways to optimize such.

  21 Responses to “Android Development – Adding Screens & Button Handlers”

  1. Nice. FYI – the warnings are more than just “style”, btw. To bad VS.NET doesn’t do the same.

    • Good point. What I’m beginning to notice is that to get the same “best practices” guidance that Eclipse gives you for free in Visual Studio, you have to shell out some non-trivial dough for a 3rd party product.

  2. There are some free things for VS.NET too (http://www.devexpress.com/Products/Visual_Studio_Add-in/CodeRushX/).

    I think VS.NET 2010 has much improved in these areas. I have not used it yet so I don’t know what for sure but I have read about them.

    • I actually have my team using the DevExpress suite of IDE tools. Great tool set. As I spin up more on Eclipse I plan on doing a more informed comparison between the two. I have a feeling that Eclipse will beat Visual Studio when it comes to “best practice” suggestions when both IDEs are used in their default configurations.

  3. [...] Android Development – Adding Screens & Button Handlers | Musings of the Bare Bones Coder [...]

  4. [...] In this short post we’ll be going over how to pass simple data between screens in an Android app. We’ll be working with the sample app we developed in a prior post, Adding Screens & Button Handlers. [...]

  5. After switching from linux after 15 years to windows 7 and trying out visual studio..I’m not quite sure what all the hype is about, that and many java IDE’s seem to be way better..if you think eclipse is nice, try intellij or jdeveloper (the community for those are nothing like eclipse, but if you’re not interested in that stuff you can get along very well). Just a thought/opinion, but anyway. Great article and thanks for your time!

    • I’ll check those 2 out once I get a little more comfortable with Eclipse. It seems like Visual Studio 2010 might have finally gotten some parity with what’s available in the Java world. The earlier versions of the IDE were rougher for sure.

  6. [...] Android Development – Adding Screens & Button Handlers – “Adding screens to an Android application is pretty straightforward. Coming from a web-centric .NET shop however, it took me a bit before I realized exactly how it was done.” [...]

  7. Very many thanks for this extremely useful article. For someone like myself who installed Eclipse on Sunday and is just feeling his way around it is just the ticket. I have created a package called My First Project.apk and it runs ok in as much as there are no runtime errors and the AVD emulator launches ok. The console output ends like this:

    2010-12-28 18:01:34 – My First Project] Performing sync
    [2010-12-28 18:01:34 - My First Project] Automatic Target Mode: launching new emulator with compatible AVD ‘AVDTarget1′
    [2010-12-28 18:01:34 - My First Project] Launching a new emulator with Virtual Device ‘AVDTarget1′
    [2010-12-28 18:01:39 - My First Project] New emulator found: emulator-5554
    [2010-12-28 18:01:39 - My First Project] Waiting for HOME (‘android.process.acore’) to be launched…
    [2010-12-28 18:02:09 - My First Project] HOME is up on device ‘emulator-5554′
    [2010-12-28 18:02:09 - My First Project] Uploading My First Project.apk onto device ‘emulator-5554′
    [2010-12-28 18:02:09 - My First Project] Installing My First Project.apk…
    [2010-12-28 18:02:30 - My First Project] Success!
    [2010-12-28 18:02:30 - My First Project] \My First Project\bin\My First Project.apk installed on device
    [2010-12-28 18:02:30 - My First Project] Done!

    All seems ok. Yes?

    Problem is when I look at the device emulator there is no sign of my application anywhere to be seen. I expected to see the icon.png sitting somewhere on the display or in the Menu. Am I wrong? What do I need to do to make this happen? Hope you don’t mind me asking.

    Thanks

    Ray

  8. nice article! wish the oficial android examples were that complete.

    only one thing: the setOnClickListener line gave me a problem in the latest version I downloaded of the SDK and eclipse

    got it running by replacing line 9 in main to:
    mainNext.setOnClickListener(new android.widget.Button.OnClickListener() {

    cheers!

  9. thanks a lot..its very useful..

  10. Thank you so much for this lesson. It helped me out alot.
    I am new to the Eclipse/Android world, but I am loving every minute of it!!
    I have been coding in VB since 1994 – I actually started with QBasic in DOS.

    Coming into this new world, I was not used to all of the manual coding that needed to be done. In the .NET world, adding a form automatically takes care of all the related code modules etc.. I couldnt quite get my head around how to make an activity, and relate it to a layout, and how to put it all together.

    I just have one question:
    On your last screen shot, you say:
    “After that, finish out the example by adding similar code to the other two screens’ onCreate method, as shown below.”

    In that screenshot, you have the code for both views / buttons / activities in the same window. Is this just for representation purposes?

    Would the code for each activity be in its own .java file? (when you added screen1.java, screen2.java)?

    I’m sorry if I’m nitpicking, I just want to make sure I have a full understanding of what I just read here.

    Thank you,
    Andrew

  11. ok so when i tried to do it the way you said to i just got a blank screen on my android whenever i clicked the button. to fix this i edited my code to get rid of the intent altogether and i typed the code as follows and it worked better than anything and is way simpler.
    Button schedRoute = (Button) findViewById(R.id.button1);
    schedRoute.setOnClickListener(new OnClickListener() {
    public void onClick(View v){
    setContentView(R.layout.scheduleone);

  12. thanks a lot…that’s what i’m looking for

  13. This helped me so much, Thankyou

    But how do you have multiple buttons on one page?
    Like instead of having one button on each page, an option so the person can choose which button they want to see?

    Thanks

  14. In my main activity, I can use they following syntax to call a sub activity:
    private void startImage(){
    Intent i = new Intent(this, ImageFromUrlExample.class);
    i.putExtra(“imagename”, image_name);
    startActivityForResult(i, ACTIVITY_GET_IMAGE);
    }

    When starting the same activity from a button in another EditActivity and using the setOnClickListener, the syntax
    Intent i = new Intent(this, ImageFromUriExample.class) does not work.
    I don’t understand why the above construct doesn’t work. Why doesn’t “this” work for the context?
    Your syntax and construct works fine and solved my problem. But why do I have to use the fully qualified “setClassName” construct for the Intent?
    Is it because of the setOnClickListener requirements?
    Thank you for solving my problem.
    TIA JohnW

  15. Excellent tutorial…

  16. We’re very good routine. how to teach clearly. Thank you very much!

  17. You are shearing great tutorials ..!!
    Please share Source Codes …Will help a lot ..

  18. Hey ! your article is really nice & i did try it..
    The thing is i got the following :

    [2012-05-02 21:17:21 - hello] Android Launch!
    [2012-05-02 21:17:21 - hello] adb is running normally.
    [2012-05-02 21:17:21 - hello] No Launcher activity found!
    [2012-05-02 21:17:21 - hello] The launch will only sync the application package on the device!
    [2012-05-02 21:17:21 - hello] Performing sync
    [2012-05-02 21:17:21 - hello] Automatic Target Mode: using existing emulator ‘emulator-5554′ running compatible AVD ‘screen’
    [2012-05-02 21:17:21 - hello] WARNING: Application does not specify an API level requirement!
    [2012-05-02 21:17:21 - hello] Device API version is 8 (Android 2.2)
    [2012-05-02 21:17:21 - hello] Uploading hello.apk onto device ‘emulator-5554′
    [2012-05-02 21:17:21 - hello] Installing hello.apk…
    [2012-05-02 21:17:30 - hello] Success!
    [2012-05-02 21:17:30 - hello] \hello\bin\hello.apk installed on device
    [2012-05-02 21:17:30 - hello] Done!

    But the hello icon is nowhere to be seen in the menu :(
    I am dng a project based on similar concept..
    please help me out at the earliest!!
    Thanks in advance !!

 Leave a Reply

(required)

(required)

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

   
© 2011 Musings of the Bare Bones Coder Suffusion theme by Sayontan Sinha