How to get started with Android development – Layout Managers

At the end of my last article, I left you hanging after describing activities, without telling you how to build a UI, so here we go. In the Android SDK, layouts are separate from the Java code that defines how an activity behaves. Using this separation of concern, it’s easier to modify the layout without having to worry about the code.

Android layouts are in XML, and are located in the res\layout folder. You can have multiple versions of a layout for various orientations, screen size or culture and the Android SDK will choose the right one according to the device. We won’t worry about this right now; for simple layouts one version is enough.

In this article, I’m going to show you how to use a layout manager to position a widget, called a View in the Android SDK, using XML and Java. Next time, I’ll complete this explanation with more details about views themselves, and how they can be controlled in the layout or programmatically.

There is also a designer tool in Android Studio to help build your layouts. I’ll stick to the code for now since I believe it’s best to understand how things are built manually first, and then you’ll know enough to be able to explore it on your own.

Your First Layout

Here is a simple layout with two TextView views, each showing a text string, inside a LinearLayout layout manager in the res\layout\activity_main.xml file:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="horizontal">

    <TextView
        android:layout_width="100dp"
        android:layout_height="100dp"
        android:text="My first textview"/>
    <TextView
        android:layout_width="100dp"
        android:layout_height="100dp"
        android:text="My second textview"/>
</LinearLayout>

Each layout has a least one view as a root, but it’s usually a layout manager such as the LinearLayout, RelativeLayout or ConstraintLayout since those views are built to position other views. I used the linear layout in this example since it’s simple to understand: if the property android:orientation is set to vertical, all the views will be aligned one over the other, and if set to horizontal they will be side by side.

To use your layout with your activity, you must set the layout in the onCreate() event of the activity using the setContentView() method :

public class MainActivity extends Activity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }
} 

Views and Layout Managers Properties

All views, including layout managers, have proprieties that can be added to their XML declaration to control their size and padding. For example, you can specify an android:layout_height and android:layout_width in dp (density-independent pixels) like the layout above, or use the wrap_content and match_parent values:

  • wrap_content: The size (width or height) of the view will be the size required to display its content. For example, if you have a very long view showing text, you’ll use wrap_content as the height so it doesn’t get truncated at the bottom.
  • match_parent: The size (width or height) of the view will be the same as the size of its parent layout element. This used to be called fill_parent in API level 7 and less, so you’ll still see that name from time to time.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
              android:layout_width="match_parent" 
              android:layout_height="match_parent" 
              android:orientation="vertical">
    <TextView android:layout_width="match_parent" 
              android:layout_height="wrap_content" 
              android:text="My first textview"/>
    <TextView android:layout_width="match_parent" 
              android:layout_height="wrap_content" 
              android:text="My second textview"/>
</LinearLayout>

Each layout manager also has properties to control the positioning of the views they contain, such as the android:orientation for the LinearLayout described previously.

Layout managers can be nested to create complex layouts: for example, you can add a vertical linear layout inside a horizontal linear layout or a grid layout. Still, to make rendering more efficient, you should be careful to avoid nesting too many layouts.

So next time, we’ll take a look at how to use complex views that requires an interaction from the user, and how control those views from your Java code.

See the other articles in the series here

How to get started with Android development – Basic structure

andro02In a previous article, I wrote about how you can launch your first Android application from the samples provided with Android Studio. Now that you’ve had a chance to poke around a few samples, I’m going to tell you a bit about the basic structure of an Android application.

A good place to start understanding an application is the manifest. The AndroidManifest.xml file links all the parts of an Android application together, including:

  • The activities contained in your application,
  • The theme you use,
  • The name of the application and its icon on the main screen,
  • The permission the application must request to run.

Activities and the java folder

The Java code of your application lives in the java folder. The first class you’ll create is a Activity class, which is the main building block of all Android applications. An activity is a full screen window in which all your code will run. Each activity has it own life cycle which starts when it’s first launched and last until it is finally destroyed.

The user navigates between different activities in your application: the back button of the device closes the current activity by default and goes back to the previous one. If the user closes the first activity of your application, he’ll go back to the application that was previously open, if any. You can also launch other applications (with their own activities) using intents. You can use this to request an application that can send an email or play music, and the installed applications that can manage this will be displayed to the user.

The activity life cycle can be affected by events outside your control: for example, if a phone call comes in, your current activity (so your application) will be paused. Each activity has a layout associated with it that describes how controls that are displayed, and the activities are declared in the AndroidManifest.xml file.

Unfortunately, the fact that the activity is bound pretty strongly to the navigation AND to the user interface/layout makes it hard to separate the business logic and the display logic properly. You can create a usable Android application with only a .java file with an Activity class, but eventually you’ll want to move on to a better architecture. There are some patterns out there that can help you do this, but for your first application you should stick with this and avoid introducing additional complexity.

Resources

Resources are everything that your application needs that is not Java code, such as layouts, strings, images and other constants. The Android API uses XML for most resources. The res folder contains all the resources of your application, such as:

  • XML layouts for each activity and component in the layout folder, styles in the values\styles.xml and images in the drawable folders. Layouts in Android are inspired by HTML/CSS, so if you’ve ever done some web development you’ll feel right at home pretty soon.
  • All the strings used in your application in values\strings.xml. You can hardcode them in the layouts, but if you ever need to translate your application you’ll be glad you put them all in one place to get started with.
  • Menus for your application are defined in the menu folder.

See the other articles in the series here

Basic JavaScript arrays reminder

I’m pretty bad when it comes to remembering syntax details for languages I don’t use every day, especially since I work with a few languages that use C-syntax and not just JavaScript. Also, it’s not the kind of details I want to spend a lot of time studying since this information can easily be found.

In most cases, it’s easy to look up how something is done in the project you’re working on, since you’ll want to follow existing patterns anyway. But since I’m working on refreshing my JavaScript knowledge and trying new patterns, I’m often faced with a blank .js file. Arrays are always one of the first things that comes up when trying to solve a problem, so I thought a quick reminder could be useful.

A standard JavaScript array is most often initialized with the bracket notation. There is also an Array object, but using the Array() constructor is not totally identical to using the bracket notation since it’s an object in that case. To keep things simple I won’t be using the object since standard arrays are a lot more common.

var fruitsArray = [];

Inserting new items at the end of an existing array is done using the push() method. The array will resize to accommodate the new items. An array can also contain any items: it is not limited to one type.

fruitsArray.push("Tomato");
fruitsArray.push("Squash");
fruitsArray.push("Potato");
fruitsArray.push("Carrot");

Removing the last item at the end of an array is done using the pop() method. In the example, the “Carrot” item will be removed.

fruitsArray.pop();

Sorting an array is done using the sort() method. By default, the items are sorted as strings, so it works for the example. For more complex cases, a sort function can be passed as a parameter to the method.

fruitsArray.sort();

Looping in an array from the start to the end using the for loop, getting the items and printing them to the console. The example also shows the length property to get the current size of the array.

for (i = 0; i < fruitsArray.length; i++) { 
   console.log(i, fruitsArray[i]);
}

Checking if a variable is an array, printing the result to the console. This condition is useful when you can’t be sure about the type of a variable, for example because you received it as a parameter.

if (fruitsArray instanceof Array)
   console.log("fruitsArray is an array");
else
   console.log("fruitsArray is not an array");

Finding an item in an array using the indexOf() method. This method returns the index of the item in the array, or -1 if the item doesn’t exist.

var itemIndex = fruitsArray.indexOf("Carrot"); // Contains -1
itemIndex = fruitsArray.indexOf("Potato");     // Now contains 0

Finally, here are all the examples in one code snippet so you execute them and try for yourself :

var fruitsArray = [];

// Inserting items
fruitsArray.push("Tomato");
fruitsArray.push("Squash");
fruitsArray.push("Potato");
fruitsArray.push("Carrot")
console.log(fruitsArray); // ["Tomato", "Squash", "Potato", "Carrot"]

// Removing an item at the end of the array
fruitsArray.pop();
console.log(fruitsArray); // ["Tomato", "Squash", "Potato"]

// Sort the array as string
fruitsArray.sort();
console.log(fruitsArray); // ["Potato", "Squash", "Tomato"]

// Length of the array
console.log(fruitsArray.length); // 3

// Looping in an array, getting the items
for (i = 0; i < fruitsArray.length; i++) { 
   console.log(i, fruitsArray[i]);
}

// Check if a variable is an array
if (fruitsArray instanceof Array)
   console.log("fruitsArray is an array");
else
   console.log("fruitsArray is not an array");

// Search for an item in an array (returns the index)
console.log(fruitsArray.indexOf("Carrot")); // -1
console.log(fruitsArray.indexOf("Potato")); // 0