Android development – Lesson 2

Android development – Lesson 2

3 603
Android development - Lesson 2

Android development – Lesson 2

This is our second lesson about developing applications for android. I hope you already enjoyed with our first lesson, and you look forward to the next lesson. This is our own series of tutorials about android development. Today we are going to learn the following: how to operate with multi-page application (or, how to work with activities), how to work with menu, how to use string resources, and finally – how to transfer variables between pages. We also will be faced with a RatingBar control element and I will show how to add event handlers directly in code.

Step 1. Create a new project (Lesson2)

First of all, please make sure that you have a necessary dev environment installed, Please install the ‘Eclipse’ program if you haven’t installed it yet. Now, we need to prepare a new project: File -> New -> Android Application Project. You can use ‘Lesson2′ for the Application Name and Project Name, on the next steps we have to select an icon for our project, lastly, select that we need to create a new Blank Activity. We can call the main window – MainWindow.

We have just created our new application !

Step 2. Pages (Activities)

Right now our application consists of one page. But how to add more pages? Now, you have to understand, that a page (or a window), is an activity (for android). Thus, to add it, we have to add a new activity. This can be done in several ways:

  • you can use the menu: File -> New -> Other
  • you can click the right mouse button in the ‘Package Explorer’
  • you can click CTRL+N

New Activity

As the first additional page – let’s create the ‘About’ page for our application.

About page

Now, as I mentioned before, I want to show you how to use predefined string resources. By default, all the sstrings are located in the ‘res/values/strings.xml’ file, open this file. Note, that you can open this file in two modes: with GUI and as a text file. Let’s use the first mode to add few more text keys. On the picture below you can see how I added the ‘about’ key value.

New string

Subsequently, you will be able to use all these strings easily in code or when you edit properties in GUI. For instance, I used the ‘about’ key as a value of the text element on our ‘About’ page.

About page with text

To finalize this page, let us add a new button ‘Close’ on the page (to close this page and back to the main window). In order to add an onclick event handler for this button, we can point a handler in settings (as we did in the first lesson), or, we can add this event handler directly in code. This is the complete code of our ‘About’ page:

package com.example.lesson2;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

public class About extends Activity {

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

		// Button click handler
		Button obClose = (Button)findViewById(R.id.buttonClose);
		obClose.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View arg0) {

				// Close the 'About' page
				finish();
				
			}
		});
	}
}

As you see, we use the ‘finish()’ to close the current activity (the ‘About’ window).

Step 3. Menu

It is pretty easy to work with the Menu in Eclipse. Open the ‘res/menu/main_window.xml’ in the Package Explorer, and, in the similar way (as we added new strings) add menu elements:

About page

Don’t forget to set element IDs, orders and titles. If you run our application now, you will notice that all the elements don’t work. We have to add a function to handle the menu elements. Open the ‘src/com.example.lesson2/MainWindow.java’ file in the Package Explorer. It contains all the functions of our main window. Now, in the menu, select ‘Source -> Override / Implement Methods’. Here, we have to find the ‘onOptionsItemSelected’ method (it is nearly in the middle), tick this method and click OK.

About page

It will add a simple overrided function:

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// TODO Auto-generated method stub
		return super.onOptionsItemSelected(item);
	}

In order to display some results on our page I created several elements on the layout of our main window: few textView elements and one editText. Now we can modify the ‘onOptionsItemSelected’:

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		TextView otResult = (TextView) findViewById(R.id.editTextMenuResult);

		switch (item.getItemId()) {
			case R.id.about:
				// Display 'About' page (activity)
				Intent opAbout = new Intent(this, About.class);
				startActivity(opAbout);
				break;
			case R.id.action_settings:
				// Display 'Settings' page (activity) and wait for result
				Intent opSettings = new Intent(this, Settings.class);
				startActivityForResult(opSettings, SETTINGS_RESULT);
				break;
			case R.id.item1:
				otResult.setText("You have selected: Item 1");
				break;
			case R.id.item2:
				otResult.setText("You have selected: Item 2");
				break;
			case R.id.item3:
				otResult.setText("You have selected: Item 3");
				break;
			default:
				return super.onOptionsItemSelected(item);
		}	
		return true;
	}

As you see, we can easily use our IDs (which we assigned during we created our menu elements) to determine which element was choosed. We used the ‘TextView::setText’ function to set a custom text for our textView element. Also, we used the ‘startActivity’ function to display the ‘About’ window (Activity) and the ‘startActivityForResult’ function to dusplay the ‘Settings’ window (because we are going to wait for a response by this window).

Step 4. Interaction between activities

I prepared another one activity (page) to demonstrate how to pass variables between activities. This new page is the ‘Settings’ page, a new ratingBar element is added on the page. Once you have clicked on the stars, this information will be sent to the main window. As usual, we have to add a necessary event handler (‘src/com.example.lesson2/Settings.java’ file), look at the code below:

package com.example.lesson2;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.widget.RatingBar;
import android.widget.RatingBar.OnRatingBarChangeListener;

public class Settings extends Activity {

	public final static String SETTINGS_RESULT = "SETTINGS_RESULT";

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

		RatingBar orRating = (RatingBar)findViewById(R.id.ratingBar1);
		orRating.setOnRatingBarChangeListener(new OnRatingBarChangeListener() {
			
			@Override
			public void onRatingChanged(RatingBar ratingBar, float rating, boolean fromUser) {
				Intent opMain = new Intent();
				opMain.putExtra(SETTINGS_RESULT, rating);
				setResult(RESULT_OK, opMain);
				finish();
			}
		});
	}
}

There is one overrided function: onRatingChanged. This function is called when we click on stars of the ratingBar element. In this moment we have to do several things: to get the main window, to pass the ‘rating’ value to this window using ‘putExtra’ function, finally, set the main result of this window (RESULT_OK) and close the window (Settings page). It is important to set the ‘RESULT_OK’ result to be sure that this window is closed properly (it means, that it was not crashed, or it was not closed by the ‘back’ button), otherwise, the ‘RESULT_CANCELED’ result will be sent. To finalize, we have to back to the main class (‘src/com.example.lesson2/MainWindow.java’ file) and add another one overrided function:

    private final static int SETTINGS_RESULT = 0;

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		super.onActivityResult(requestCode, resultCode, data);

		// catch Settings page result
		if (requestCode == SETTINGS_RESULT && resultCode == RESULT_OK) {
			// Get settings vote result and display it on the main page
			float fRes = data.getFloatExtra(Settings.SETTINGS_RESULT, 0);
			TextView otSettingsResult = (TextView) findViewById(R.id.textViewSettingsResult);
			otSettingsResult.setText(fRes + " stars");
		}
	}

In this code you can see that we can recognize a responded page and a result code which was sent by this page.



Conclusion

We have just finished the second lesson about android development for the beginners. I hope that you like it and it is useful for you. Good luck and welcome back to our further lessons

SIMILAR ARTICLES


3 COMMENTS

Leave a Reply