Creating a Custom Scalable background

The Android SDK provides a very powerful feature which helps you create cool looking backgrounds for your views and widgets. The best part is you do not have to create or resize any images to fit any device screens and the whole thing is based on simple xml files. And you don’t have to waste time in scaling a lot of images.

To create a custom background file create a custom XML file in the /res/drawable folder in the project and later it can be referenced using the android:background attribute of any view or widget.

You would need to use the <shape> element in the XML file and then define the attribute of the shape, the shape can be a rectangle, oval, line or ring. Though the most commonly used shape is rectangle.

In the example below we create a rectangle with rounded corners and use a gradient to color the background. Also the rounded rectangle has a border of 5 dip.

Step 1:

Right click on the res folder in the project >> New >> Android XML File

Step 2: Select the Resource Type as Drawable and select the Root Element as shape and name the file eg. Gradientbg.

This will create a gradientbg.xml under the drawable folder under the res folder and open the XML file in the code window.

Step 3: Modify the xml file as follows:

<?xml version="1.0" encoding="utf-8"?>

<shape xmlns:android="http://schemas.android.com/apk/res/android"

android:shape="rectangle" >

<gradient android:angle="270" android:endColor="#CEECF5" android:startColor="#00BFFF" android:type="linear" >
</gradient>

<corners android:radius="20dip" /><stroke android:width="5dip" android:color="#000" /></shape>

android:shape defines the shape of the background it coud be rectangle,oval,ring or line.

<gradient> tag provides the startcolor and the endcolor and the angle in multiples of 45, also type which could be linear,radial or sweep.

<corners> only applies to the shape rectangle and the radius provides the degree of roundness for the corners.

<stroke> provides a border to the rectangle which has a width and a color.

Once the XML file is compiled it can be used in any view or widget by defining the android:background = “@drawable/gradientbg” where gradientbg is the XML file name.

The following screen shot shows the background applied on the whole activity by applying the background on the root layout.

In the next screenshot the same background is applied on a button widget.

Dynamically adding widgets to a User interface

Normally the views defined using the XML layout field can be simply inflated by using the setContetntView(R.layout.main).

The following code is used to add a button dynamically:

public void onCreate(Bundle savedInstanceState) {
   super.onCreate(savedInstanceState);

   //Inflate the layout file res\layout\activity_uc.xml

   LinearLayout layout = (LinearLayout)getLayoutInflater().inflate(R.layout.main,null);

   //Initiate a new button

   Button reset = new Button(this);
   reset.setText("Reset Form");

   //Add the new button to the layout

   layout.addView(reset,new LinearLayout.LayoutParams(LayoutParams.FILL_PARENT,

   LayoutParams.WRAP_CONTENT));

   //Attach the view to the window

   setContentView(layout);

}

Interface created using a Layout XML 

Interface created after adding a button dynamically

Creating a One activity Application

Overview

We are going to design a simple application which basically converts between different units of Measurement.  And the user can select an option from a dropdown(called Spinner in Android) and enter the quantity needed to be converted in a Textbox and click on the Convert button and the converted value is displayed in the same textbox(EditText in Android). A Clear button clears the EditText and a Close button closes the application.

We will start with a rough prototype and then build on it in future and try to improve and optimize it in different ways.

Let’s get going

Designing the interface

As can be seen from the requirements the interface would need the following widgets:

1. EditText ( Textbox)

2.TextView (Label)

3. Spinner (Dropdown box)

4. Button

Let’s design a layout in the Eclipse. Open the main.xml in the res/layout directory

And drag and drop the widgets required , start with the LinearLayout from the layouts section. Try to emulate from the highlighted section. Do not worry about the appearance too much.

Once done with the interface, name the widgets properly(By selecting the widget in Outline section and going to properties section) so that you can reference them from the code.

Once you have added the widgets, its time to launch the application and see your work of Art .;)

Of course the buttons or the spinners won’t work because we haven’t added event handlers for them.

Step 2:

Populating the Spinner widget. (Android Spinner, XML resources, Adapter)

We will be populating the Spinner using values from an XML file. This is the best way to decouple the business logic from the User interface. Android provides options to create different types of XML resources , for the time being just goto the res/values and right click on it >> New >> Android XML File

Select the Resource Type as Values and click Finish.

Copy and Paste the XML below. As can be seen from the XML file we have defined 2 arrays :

  1. conversions : Used to populate the spinner.
  2. multipliers: Used in the conversion calculation.
<?xml version="1.0" encoding="utf-8"?>

<resources>

	<string-array name="conversions">

		<item>Pounds to Kgs</span></item>

		<item>Kgs</span> to Pounds</item>

		<item>Kilometers to Miles</item>

		<item>Miles to Kilometers</item>

		<item>Degrees Celsius</span> to Degrees Fahrenheit</span></item>

		<item>Degrees Fahrenheit</span> to Degrees Celsius</span></item>

	</string-array>

	<string-array name="multipliers">

		<item>0.450</item>

		<item>2.20462</item> <!-- Acres to Square Miles -->

		<item>0.621371</item> <!--Atmospheres to Pascals</span>  -->

		<item>1.60934</item> <!--Bars to Pascals</span> -->

		<item>0</item> <!--Degrees Celsius</span> to Degrees Fahrenheit</span> -->

		<item>0</item> <!--Degrees Fahrenheit</span> to Degrees Celsius</span>  -->

	</string-array>

</resources>

Eclipse power tip : To Beautify any code in Eclipse IDE use Ctrl+Shift + f for windows and Command + shift+ f for Mac.

Save the XML file and get back to the code window.

Add the following code

// Getting a reference to the Spinner from the layout

final Spinner spnConversions = (Spinner) findViewById(R.id.conversions);

// Creating the items from the Array resource

ArrayAdapter<CharSequence> aa = ArrayAdapter.createFromResource(this,

R.array.conversions,

android.R.layout.simple_spinner_item);

//Setting the spinner item look from android layouts

aa.setDropDownViewResource(android.R.layout.simple_spinner_item);

// Populating the spinner with the XML data

spnConversions.setAdapter(aa);

Run the application and you should see the items once you click on the small down arrow on the spinner.

Add the following code for attaching a listener to the spinner widget.

AdapterView.OnItemSelectedListener spinlistener = new OnItemSelectedListener() {

public void onItemSelected(AdapterView<?> arg0, View arg1,
int position, long id) {
//save the selected position
MainActivity.this.position = position;
}

public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub

}
};
//attaching the listener
spnConversions.setOnItemSelectedListener(spinlistener);

The code snippet saves the position of selected item. Declare a private attribute in activity named position.

Next add the listeners for the Clear and the Close buttons.

// Adding listener for the close button

Button btnClose = (Button) findViewById(R.id.close);

View.OnClickListener btnCloselistener = new View.OnClickListener() {

public void onClick(View v) {

//closing the application

finish();

}

};

// Attaching the listener to the button

btnClose.setOnClickListener(btnCloselistener);

// Adding listener for the close button

Button btnClear = (Button) findViewById(R.id.clear);

View.OnClickListener btnClearListener = new OnClickListener() {

public void onClick(View v) {

//clearing the text from EditText

txtValue.setText(“”);

}

};

// Attaching the listener to the button

btnClear.setOnClickListener(btnClearListener);

This finishes the simple application; we will be building on the application in the next coming up tutorials.

Creating a plug and play Android development environment

This one is for the new Android developers or the ones who want to get into Android development. With the steps given below , anyone can create a self-sufficient environment for Android development. It is useful due to the following reasons:

  1. Deploy the environment across many PCs, update the APIs only once and and copy it to other systems.
  2. In case the working environment gets  corrupt , just replace it with the saved installation.

Let’s get going….

Step 1:

Download the latest Eclipse Ide from the Eclipse download site, I prefer the win-32 version even if I have 64-bit system as sometimes it leads to conflict with the JVM.

Step 2:

Download and install the Android SDK from http://developer.android.com/sdk/index.html, it will get installed in C:\Program Files (x86)\Android\Android-SDK. Make sure you know where you are installing the SDK.

  • Once the SDK is installed download all the needed APIs for Different platforms by running SDK Manager.exe from the installation folder.

Step 3:

Open Eclipse and install the ADT plugin .

  • Goto Help>> Install New Software

  • Select the Developer tools option and click on next , Accept the EULA and let it install.

Step 4:

Once the ADT plugin is installed we move to the next step, Goto C:\Program Files (x86)\Android\ and copy or cut the Android-SDK folder and paste it where the Eclipse installation is eg. C:\Data.

Step 5:

The last step is to update the SDK location in Eclipse ,  Go to  Window>> Preferences >> Android  >> SDK Location and update it to the new location where you moved your Android-SDK folder.

Once all the steps are complete you can create a zipped folder from the C:\Android folder and reuse it on other systems or keep it in a secure place for any contingencies later.  🙂

For the newbs who do not want so much configuration, they can download the pre-installed rar file here.

It includes: Eclipse Juno , Android SDK, Android APIs, and the ADT plugin .(Also included is the GIT plugin)

Activity LifeCycle

The following methods define the entire lifecycle of an activity. By implementing these methods, you can monitor three nested loops in the activity lifecycle:

  • The entire lifetime of an activity happens between the call to onCreate() and the call to onDestroy(). Your activity should perform setup of “global” state (such as defining layout) in onCreate(), and release all remaining resources in onDestroy(). For example, if your activity has a thread running in the background to download data from the network, it might create that thread in onCreate() and then stop the thread inonDestroy().
  • The visible lifetime of an activity happens between the call to onStart() and the call to onStop(). During this time, the user can see the activity on-screen and interact with it. For example, onStop() is called when a new activity starts and this one is no longer visible. Between these two methods, you can maintain resources that are needed to show the activity to the user. For example, you can register a BroadcastReceiver inonStart() to monitor changes that impact your UI, and unregister it in onStop() when the user can no longer see what you are displaying. The system might call onStart() and onStop() multiple times during the entire lifetime of the activity, as the activity alternates between being visible and hidden to the user.
  • The foreground lifetime of an activity happens between the call to onResume() and the call to onPause(). During this time, the activity is in front of all other activities on screen and has user input focus. An activity can frequently transition in and out of the foreground—for example, onPause() is called when the device goes to sleep or when a dialog appears. Because this state can transition often, the code in these two methods should be fairly lightweight in order to avoid slow transitions that make the user wait.

Following  figure illustrates these loops and the paths an activity might take between states. The rectangles represent the callback methods you can implement to perform operations when the activity transitions between states.

Starting an activity for a result

Sometimes, you might want to receive a result from the activity that you start. In that case, start the activity by calling startActivityForResult() (instead of startActivity()). To then receive the result from the subsequent activity, implement the onActivityResult() callback method. When the subsequent activity is done, it returns a result in an Intent to your onActivityResult() method.

For example, perhaps you want the user to pick one of their contacts, so your activity can do something with the information in that contact. Here’s how you can create such an intent and handle the result:

private void pickContact() {

// Create an intent to "pick" a contact, as defined by the content provider URI

Intent intent = new Intent(Intent.ACTION_PICK, Contacts.CONTENT_URI);

startActivityForResult(intent, PICK_CONTACT_REQUEST);

}

@Override

protected void onActivityResult(int requestCode, int resultCode, Intent data) {

// If the request went well (OK) and the request was PICK_CONTACT_REQUEST

if (resultCode == Activity.RESULT_OK && requestCode == PICK_CONTACT_REQUEST) {

// Perform a query to the contact's content provider for the contact's name

Cursor cursor = getContentResolver().query(data.getData(),new String[] {Contacts.DISPLAY_NAME}, null, null, null);

if (cursor.moveToFirst()) { // True if the cursor is not empty

int columnIndex = cursor.getColumnIndex(Contacts.DISPLAY_NAME);

String name = cursor.getString(columnIndex);

//         Do something with the selected contact's name...

}

}

}

 

This example shows the basic logic you should use in your onActivityResult() method in order to handle an activity result. The first condition checks whether the request was successful—if it was, then the resultCodewill be RESULT_OK—and whether the request to which this result is responding is known—in this case, therequestCode matches the second parameter sent with startActivityForResult(). From there, the code handles the activity result by querying the data returned in an Intent (the data parameter).

What happens is, a ContentResolver performs a query against a content provider, which returns a Cursorthat allows the queried data to be read. For more information, see the Content Providers document.

For more information about using intents, see the Intents and Intent Filters document.

Starting an Activity

What is an Activity?

An activity in android is the user interface that is used to interact with the user. Simply said any android application is made up of one or more activities(screens). The activity is made up of Viewgroups and views. Viewgroups are basically layout for the screen eg. Linearlayout is used to layout the widgets (buttons, text-box etc. ) in a linear manner ie. either horizontally or vertically.   Any activity could start any other activity.

How to start?

Its very important to declare the activity in the android manifest file (AndroidManifest.xml) to make it visible to the system. The declaration looks something like this:

You can start another activity by calling startActivity(), passing it an Intent that describes the activity you want to start. The intent is the heart of the android system it is used to start activities , services and  broad cast receivers. The intent specifies either the exact activity you want to start or describes the type of action you want to perform (and the system selects the appropriate activity for you, which can even be from a different application). An intent can also carry small amounts of data to be used by the activity that is started.

When working within your own application, you’ll often need to simply launch a known activity. You can do so by creating an intent that explicitly defines the activity you want to start, using the class name. For example, here’s how one activity starts another activity named SignInActivity:

Intent intent = new Intent(this, SignInActivity.class);

startActivity(intent);

However, your application might also want to perform some action, such as send an email, text message, or status update, using data from your activity. In this case, your application might not have its own activities to perform such actions, so you can instead leverage the activities provided by other applications on the device, which can perform the actions for you. This is where intents are really valuable—you can create an intent that describes an action you want to perform and the system launches the appropriate activity from another application. If there are multiple activities that can handle the intent, then the user can select which one to use. For example, if you want to allow the user to send an email message, you can create the following intent:

Intent intent = new Intent(Intent.ACTION_SEND);

intent.putExtra(Intent.EXTRA_EMAIL, recipientArray);

startActivity(intent);

The EXTRA_EMAIL extra added to the intent is a string array of email addresses to which the email should be sent. When an email application responds to this intent, it reads the string array provided in the extra and places them in the “to” field of the email composition form. In this situation, the email application’s activity starts and when the user is done, your activity resumes.