Thursday, January 27, 2011

Formatting Android Layout XML in Eclipse

Sometimes when you are editing Android Layouts in Eclipse, it makes more sense or is more convenient to change the actual xml content. The problem is, a lot of the time the xml is not pretty to look at. Lines of text often run off the screen and it is difficult to tell where one element begins and another ends.

Messy Android Layout XML
But fear not!

Eclipse has some handy auto-formatting tools. Press Ctrl+Shift+F to auto-format the selected file. Or from the menu, click Source->Format.

Formatting Menu Option

Now your file will be cleaned up and easier to edit.


Formatted Android Layout XML

If you have text selected, only the selected text will be formatted. If no Text is selected, the entire file will be formatted. And Auto-Format will work on your Java files too.

Tuesday, January 25, 2011

Android Button Tutorial

In this tutorial we will create a simple Android App that responds to input from a button. Every time the button is clicked, an onscreen counter will update showing the total number of clicks.

Most Android apps involve using buttons to direct actions within the activity. Think about the built in calculator application. It is essentially made up of just a bunch of buttons. They may not look like the standard, buttons, but it is possible to skin Android buttons to look however you want.

Screenshot of the Android calculator.
Android Button Example

Step 1. Create a new Android project

Start a new android project. Call the project "Button Tutorial" and set the package name to "example." Check the "Create Activity" checkbox in the wizard and set the activity name to "MainActivity" If you need help see this tutorial for more information on creating a "Hello World" project.

Step 2. Create a layout that includes a button

For a full tutorial on create layouts, click here for the android layout tutorial.

Open up the layout file main.xml. Make sure the following properties are set for the parent linear layout.

Layout height: fill_parent 
Layout width: fill_parent 
Orientation: vertical

If there isn't a TextView in the layout already, add one. Set the following properties.

Id: @+id/TextViewCount
Text: "Count"
Text Size: 40dip


Layout height: wrap_content 
Layout width: fill_parent 
Layout margin bottom: 10dip


Now, add a Button to the layout, and set the following properties.

Id: @+id/ButtonCount
Text: Count
Min width: 125dip

Layout height: wrap_content
Layout width: wrap_content
Layout gravity: center


Feel free to adjust the properties as you see fit. Listed below is a screenshot of the layout we have created.

Screenshot of the layout created.

Make sure to save your layout after you have modified it. When you save the layout, the generated Java class, R, will be recreated to include the ids of any new elements you have added to the layout.

Step 3. Add a OnClick listener to the button

Now that we have created the layout, its time to edit the actual Java code that is the logic behind the program. Open up MainActivity. It is located under src->example->MainActivity.java in the project explorer.

Screenshot of the MainActivity generated code


Let's examine the code that is already there.

MainActivity extends the Activity class. Activities are the main components of Android Applications. The onCreate method gets called when the parts of the activity need to get built. The first line calls the super constructor, and the second line sets the layout of the activity.

Now add a member variable that will keep track of the count. The complete code for the activity so far is listed below.

package com.dreamdom.tutorials.buttontutorial;

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

public class MainActivity extends Activity {

    // Private member field to keep track of the count
    private int mCount = 0;

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



About Android Resources

The Android Developer Tools make it really easy to reference the components inside of your resources folder. The ADT will automatically generate a Java file, R, that contains unique integer ids for all your resources. These generated IDs can then be used in your Java code to reference the resources.

Do not modify the file R.java!

R.java is located inside "gen" folder for generated java files. You should never be editing generated files because you will likely
  1. Cause a problem
  2. Have your changes overwritten almost immediately
  3. Give yourself lots of headaches
If you modify your project to add a layout or a new drawable the file R.java will automatically get regenerated. On occasion you can run into problems, but these are generally solved by going to Project->Clean to regenerate many of the files.

Step 4. Obtaining references to the views

Now we want to obtain references to the views we created in the layout. We need these references in the Java file so that we can program the logic behind how they operate. Add the following code just below the setContentView... line

final TextView countTextView = (TextView) findViewById(R.id.TextViewCount);
final Button countButton = (Button) findViewById(R.id.ButtonCount);

You will need to add the following lines at the top of your project.

import android.widget.TextView;
import android.widget.Button;

If you are still getting errors as part of "R.id...." make sure that you have saved the layout after modifying it.

Now that we have references to these views we can modify them in all sorts of ways through the Java code. Most of the properties we've set in the layout editor can also be set by using member functions for the views.

Step 5. Add a onClickListener to the Count Button

Now that we have a reference to the count button, we want to add a listener that handles when the count button is clicked. An easy way to do this is to have an anonymous class implement the View.OnClick interface. The Code listed below demonstrates this.

countButton.setOnClickListener(new OnClickListener() {
    
    public void onClick(View v) {
        
    }
});

Make sure to add the following code to the top of the file.

import android.view.View;
import android.view.OnClickListener

Step 6. Fill in the counting logic

Now we just need to fill in the logic that will increment the count, and update the value of the text view. Add the following code inside of the onClickListener that you just created.

mCount++;
countTextView.setText("Count: " + mCount);

Step 7: The finished product

Finally, run your project and press the count button. You should see the count on the screen go up.

Screenshot of the finished app



Full code for MainActivity.java
package com.dreamdom.tutorials.buttontutorial;

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

public class MainActivity extends Activity {
    
    // Private member field to keep track of the count
    private int mCount = 0;
    
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        final TextView countTextView = (TextView) findViewById(R.id.TextViewCount);
        final Button countButton = (Button) findViewById(R.id.ButtonCount);
        
        countButton.setOnClickListener(new OnClickListener() {
            
            public void onClick(View v) {
                mCount++;
                countTextView.setText("Count: " + mCount);
            }
        });
        
    }
}


Full code for main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="fill_parent"
    android:layout_height="fill_parent">
    <TextView android:layout_width="fill_parent"
        android:layout_height="wrap_content" android:text="Count" android:id="@+id/TextViewCount"
        android:textSize="40dip" android:layout_marginBottom="10dip" />

    <Button android:layout_width="wrap_content"
        android:layout_height="wrap_content" android:layout_gravity="center"
        android:text="Count" android:id="@+id/ButtonCount" android:minWidth="125dip"></Button>
</LinearLayout>

As always, please leave any questions you have in the comments area, and I will be glad to help!

------------------------------------------------------------

We create these tutorials in our free time. If you like what you see please consider buying us a cup of coffee so we can keep creating useful material. Click on the image below to make a donation via Paypal.

Wednesday, January 19, 2011

Android Layout Tutorial

Android layouts can be very intimidating at the first look. Instead of a grid where you can drag components to precise absolute positions, you are greeted with xml code and a WYSIWYG (What you see is what you get) editor that doesn't seem to behave the way you want it to.

It's enough to drive you insane and, for some, enough to put you off on Android development entirely.

But don't despair! Follow these tips and you will be making layouts in a flash. You may even learn to love Android XML Layouts.

This tutorial assumes that you have the Eclipse IDE set up for Android development, and know how to make a "hello world" application. For more detailed instructions on how to do that, visit this link http://developer.android.com/guide/developing/eclipse-adt.html

Dom's Steps:

1. Prototype on Paper

This is a crucial step. It can help to organize your thoughts and lead to less headaches and frustrations when you actually start to design for real. One strategy is to used a notecard for the layout sketch. Notecards provide a rough approximation of the size of an Android smartphone.

A notecard next to an Android phone


If you want to be more organized, I recommend using a notebook or a sketchbook so you can keep multiple layouts for a single app together.

For this tutorial we are going to pretend that we are creating a layout for part of a simple twitter application. The completed sketch is shown below.

A sketch of the layout

2. Start thinking in terms of Linear Layouts and Views

Now that you have a sketch of what you want your layout to look like, start picturing the pieces of the drawing as views.

An Android layout is made up of views. Views are components like Buttons, Images, and Text Inputs. These views can organized in a number of sub layouts.

I recommend sticking using LinearLayouts to organize your views. LinearLayouts are simple, easy to modify, and can handle mostly anything. A lot of times it seems easy to think in terms of tables, but Table Layouts are not as flexible, and will usually end up causing problems and frustration as you try to modify them. TableLayouts force equal column width, and make it difficult to span columns.

3. Start a New Layout in Eclipse.

To start, create a simple "Hello World" type application. See this tutorial for more information. I chose to create an Android 1.5 project, but you can choose a different version if you like.

In the project explorer right click on the layout folder and select "New Android XML File" Type in layout.xml as the name, and make sure the type of resource selected is layout.

The layout folder in the project explorer


The WYSIWYG in Eclipse can be difficult at times but it makes designing layouts easier by giving you the outline view on the right, and the property list editor at the bottom. Click the element named LinearLayout in the outline view.

The outline view

Now you can easily change the properties associated with the outline view from the properties view. The properties view is generally located at the bottom of the screen, next to the console output. If you can't see it go to Window->Show View->Other...->General->Properties.




Make sure the following properties are set for the outline view.

Misc->Layout Height: Fill Parent
Misc->Layout Width: Fill Parent
Orientation: Vertical

Now set the background property to #ffffff. The background should turn white. You can enter any valid hexadecimal color code to set the background.

4. Add the Views for the First Row

Now that we have the base layout set, we want to add another LinearLayout to hold the views for the first row. Click the plus button on the outline view to add another LinearLayout.

Note: At the time of the publishing of this article the current version of the Android Developer Tools does not include the plus, up arrow, and down arrow buttons. It is currently unclear whether this was intentional or a bug. You can still add components by dragging them from the list on the left, onto the preview display on the right.

Screenshot showing the list of views to add on the left, and the display preview in the middle

Set the following properties.


Orientation: Horizontal
Misc->Layout Width: Fill Parent

ID's should be unique within an xml layout file, but they do not have to be unique among all the xml layout files. When you add an element, the sdk will automatically generate a valid ID for the element, but it can be helpful to change the id to a more recognizable name.

Now add the views to the first row. Click the plus button to add an ImageView. Click the plus button again to add a TextView. Use the up and down arrows to adjust the order of the views and make sure they have the proper parent element.

The outline view should now look like this.



Copy the following image to the drawable directory of project. Name it headonly.png

headonly.png

Depending on what target version (Android 1.5, 1.6, 2.0, etc...) of the Android OS you have selected, you will also notice that they place three different folders as the drawable directory: drawable-hdpi, drawable-ldpi, and drawable-mpdi. This stand for high, medium and low density-independent pixel. And were designed to further customize the applications depending on the type of phone (some support better graphics). To learn more please visit: http://developer.android.com/guide/practices/screens_support.html.

For now we'll be storing our images under the drawable-hpdi folder. Even though the picture is in a specific folder (hdpi) set the source to @drawable/headonly and Android will figure out where to look for the image.

Now set a few of the properties for the views you just added.

ImageView01->Padding: 7dip
ImageView01->Src: @drawable/headonly

TextView01->Text color: #000000
TextView01->Text size: 30dip
TextView01->Text: Twitter Name
TextView01->Misc->Layout gravity: Center
TextView01->Misc->Layout margin left: 10dip

The layout should look like this now.

The current progress of the layout


If you are having problems placing the components make sure the parent layers have the right settings. One possible problem is having the parent layer set up to get the height of the parent instead of wrapping, which made the text appear in the middle of the screen.

What is DIP?
DIP stands for density independent pixels. Since different devices can have different dpi's, specifying measurements in DIP instead of pixels can help ensure a more consistent look and feel among different devices.


5. Adding the ListView

ListViews are one of the most versatile Android components. They let you combine may different items that have a similar layout into a object that has built in scroll and flick capabilities.

We will add the ListView to the layout in this tutorial. Populating the ListView with actual data is handled programmatically and beyond the scope of this tutorial.

Select LinearLayout from the outline window and then drag and drop the ListView. Now LinearLayout is the parent of ListView. If the arrows on the outline view are visible (see earlier note) you can use them to adjust the hierarchy of the views so that the parent of the ListView01 is LinearLayout.

Set the following property.

ListView01->Misc->Layout Weight: 1

Setting the layout weight as a value of 1 tells the list view to take up all the remaining available space.



6. Adding the Bottom Row

Select the top LinearLayout and drag and drop another linear layout. By default it will go to the end of the list. Set the following properties.


Orientation: Horizontal

Misc->Layout Width: Fill Parent
ID: @+id/ButtonLayout

Screenshot of where to change the id

This linear layout should be underneath the ListView in the Orientation View, and have this new LinearLayout as its parent. Feel free to rename this LinearLayout as

Add three buttons to ButtonLayout. Set the following property for all the buttons.

Layout weight: 1
Layout width: 100dip

Set the text for the three buttons to be Share, Search, and Retweet. By setting the weights and the widths the same, the three buttons should equally share the width of the available screen.


A note about adding the buttons with Drag and Drop

After setting up the properties of the linear layout if you try to drag and drop the buttons it won't work, they won't be added as the child of the last linear layout. So here is Silvia's trick: for the ButtonLayout choose the layout height to be the same as the parent. Now if you select it and drag and drop the buttons, these will be added in the right hierarchy. It is important that as soon as you finished adding the buttons you return the button layout to wrap layout height.


6. The Finished Layout

The finished layout should look like this.

The finished layout


The complete xml for the layout is pasted below. When you are using Eclipse to view the xml, pressing Ctrl+Shift+f will auto format the xml. to make it look nicer.

The full xml of the layout:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
 android:orientation="vertical" android:layout_height="fill_parent"
 android:layout_width="fill_parent" android:background="#ffffff">
 <LinearLayout android:layout_width="wrap_content"
  android:layout_height="wrap_content" android:id="@+id/LinearLayoutFirstRow">
  <ImageView android:id="@+id/ImageView01"
   android:layout_width="wrap_content" android:layout_height="wrap_content"
   android:src="@drawable/headonly" android:padding="7dip"></ImageView>
  <TextView android:id="@+id/TextView01" android:layout_width="wrap_content"
   android:layout_height="wrap_content" android:textSize="30dip"
   android:textColor="#000000" android:text="Twitter Name"
   android:layout_gravity="center" android:layout_marginLeft="10dip"></TextView>


</LinearLayout>

<ListView android:id="@+id/ListView01" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_weight="1">
</ListView>

<LinearLayout android:id="@+id/LinearLayout01" android:layout_height="wrap_content" android:layout_width="fill_parent" android:orientation="horizontal"><Button android:id="@+id/Button01" android:layout_height="wrap_content" android:layout_weight="1" android:text="Share" android:layout_width="100dip"></Button>
<Button android:id="@+id/Button02" android:layout_height="wrap_content" android:layout_weight="1" android:text="Search" android:layout_width="100dip"></Button>
<Button android:id="@+id/Button03" android:layout_height="wrap_content" android:layout_weight="1" android:text="Retweet" android:layout_width="100dip"></Button>


</LinearLayout>
</LinearLayout>

Monday, January 17, 2011

Two Categories of Tutorials

As I plan out a list of tutorials for the Blog, I have decided to group the tutorials into two different categories -- Beginner Tutorials and Advanced Tutorials. I thought about having a third category of intermediate tutorials, but then I couldn't think of any clear cut examples of what would qualify.

Beginner tutorials will be directed towards people who may have some programming experience, but are new to the Android platform. The goal of these tutorials is to provide a thorough introduction to many Android concepts and to provide examples that are practical applications. These tutorials will build off of each other.

Examples of some beginner tutorials I have planned:



Advanced tutorials will assume more knowledge of Android concepts, and can be read a-la cart. Many of them will be based off of situations that I encountered that gave me some trouble in building my apps.

Examples of some advanced tutorials I have planned:

  • Scanning storage for media files
  • Animating views
  • Fading one image into another

    One final note, please feel free to comment on the blog and request for a tutorial on a certain concept. I will try to answer any questions that people ask.

    Sunday, January 16, 2011

    Creating the Hello World Project



    Most of the tutorials on this site can be built off of a simple "Hello World" type app.

    By using some of the Wizards in the Android Developer Toolkit, the "Hello World" project can easily be created and turned into another app, by automatically creating an Activity, Layout, and updating the application manifest.

    The official Android website has a great tutorial on getting the hello world project set up. You can find the tutorial here http://developer.android.com/resources/tutorials/hello-world.html


    Friday, January 14, 2011

    Welcome to Android Dom

    Welcome to Android Dom!

    Here I will be posting various tips, tricks, and perhaps a couple of complete tutorials on how to make android apps.

    Please stop by often, as I plan to update this blog on a weekly basis.