Android Development 101: Simple App

I’m going to learn Android development, so I’m going to post a series of tutorials on basic android development. No need to explain more, here we go:

First off, I’m assuming you followed the setup guide here (http://developer.android.com/training/index.html) and have eclipse with the android development tools installed. Next we are going to make an app with two buttons. When you click one, you display a message that it was clicked, you also log the a message to the console (one of the first things you should do as a developer is figure out how to debug – log things to the console). It will look something like this:

I’m assuming you created a new android application project and named it appropriately. No need for me to write something new here, there’s a great resource on the android site (http://developer.android.com/training/basics/firstapp/creating-project.html).So lets get started, the first thing we need to do is adjust the layout to display our buttons and text. This is easily done in APP_NAME –> res –> layout –> activity_main.xml (or whatever you might have changed it to under the same folder). I’ll explain what each of these things mean in the comments in the xml file.

<!-- Set the layout to linear so all elements stack below on another -->
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <!-- Put your intro copy here -->
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/intro_text" />

    <!-- The first button with an ID of "button_start" it also calls a string of text with name "button_start" -->
    <Button
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:id="@+id/button_start"
        android:text="@string/button_start" />

    <!-- The second button with and ID of "button_stop", it's text is called with the name "button_stop" -->
    <Button
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:id="@+id/button_stop"
        android:text="@string/button_stop" />

</LinearLayout>

Don’t worry about much right now other than the fact that we want the layout to be vertically stacked and all elements to take up the full width of the page and wrap if they need to for the height of the content. You can assign ids to elements by calling:

android:id="@+id/ELEMENT_ID"

This tells the android app where to look for this element. We’ll use this later to look for a click event on the buttons.

If you’ve successfully copied this code above, eclipse will start to complain that you don’t have strings attached to the “android:text” attributes. It’s right, let’s put that information in next.

Under APP_NAME –> res –> values –> strings.xml , you need to input the strings. These are the text that you want displayed, in our case for our intro text and buttons. You can see above we are inserting something called “android:text=’@string/intro_text'” in our TextView element. Let’s define that first. Your input should look like the following:

You can see in the image, the arrow points to the name we gave the string. This helps us separate content from layout. Simply name a string, define the string’s value and you’ve connected the two points. Do the same for the two buttons:

Now you have all the strings defined. At this point your eclipse + ADT should not be complaining. You can run the app and see that there are two buttons and some text at the top. Great! Let’s get those buttons working.

In APP_NAME –> src –> com.example.APP_NAME –> MainActivity.java you should see some predefined code. I’ll paste the full code in and explain what it’s doing:

package com.example.simpleapp8;

// import the necessary packages
// as you code, if you require a package, simply hit ctrl + shft + o to auto-import the packages you need
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;

public class MainActivity extends Activity {

	// a string we are going to use to name the app in the logs
	private static String logtag = "Simple App 8";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // find your buttons
        Button startButton = (Button)findViewById(R.id.button_start);
        Button stopButton = (Button)findViewById(R.id.button_stop);

        // listen for clicks on the buttons
        startButton.setOnClickListener(startListener);
        stopButton.setOnClickListener(stopListener);
    }

    // create a new click listener known as "startListener"
    private OnClickListener startListener = new OnClickListener() {
    	// run a function called "onClick" and pass in a view object
    	public void onClick(View v) {
    		// log the button event
    		Log.d(logtag, "button clicked - start button");
    		// present a popup to the user with a message
    		Toast.makeText(MainActivity.this, "button clicked - start button", Toast.LENGTH_LONG).show();
    		// log the button end
    		Log.d(logtag, "button ended - start button");
    	}
    };

    // same thing as above except for the stopListener this time
    private OnClickListener stopListener = new OnClickListener() {
    	public void onClick(View v) {
    		Log.d(logtag, "button clicked - stop button");
    		Toast.makeText(MainActivity.this, "button clicked - stop button", Toast.LENGTH_LONG).show();
    		Log.d(logtag, "button ended - stop button");
    	}
    };

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    /**
     * Below are some helpful app wide event listeners to let you know when the app has reached
     * certain states, for instance when the user hits the home button, the app with pause. When the
     * user re-opens the app, you can look for "onResume" and take action like presenting a message
     * that says "Welcome Back!"
     */
    @Override
    protected void onStart() {
    	Log.d(logtag, "started");
    	super.onStart();
    }

    @Override
    protected void onResume() {
    	Log.d(logtag, "resumed");
    	super.onResume();
    }

    @Override
    protected void onPause() {
    	Log.d(logtag, "paused");
    	super.onPause();
    }

    @Override
    protected void onStop() {
    	Log.d(logtag, "stopped");
    	super.onStop();
    }

    @Override
    protected void onDestroy() {
    	Log.d(logtag, "destroy");
    	super.onDestroy();
    }

}

It looks like a lot, but it’s actually pretty simple. It’s just finding the buttons we defined earlier, setting some onClick events on them and displaying a message if a user clicks. The rest of the code are just some helpful functions to allow you to determine what the state the app is in and entering into so you can take whatever actions you please.

The last item is the tricky part. Let’s say we don’t want the app to rotate when a user turns their phone sideways. We need to modify APP_NAME –> AndroidManifest.xml. Let’s add:

android:screenOrientation="protrait"

To the activity element. Here’s a screenshot

Now we’ve locked the screen orientation to portrait.

That’s it for round 1. More to come. I got this post from here (http://blog.idleworx.com/2011/06/build-simple-android-app-2-button.html), I’m just mostly repeating this for my own sake.

 

 

Leave a Reply

Your email address will not be published. Required fields are marked *