Android

Build your First Android App using Android Studio

This tutorial will teach you the basics of how to build an Android app using the Android Studio development environment. Java is the language used by Android.

1. Install “Android Studio IDE” and “Android SDK”

1.1 Installing “Android Studio IDE”

  1. Uninstall older version(s) of “Android Studio” and “Android SDK”, if any.
  2. Check the system requirements for Android Studio/SDK @ https://developer.android.com/studio#Requirements
  3. Go to https://developer.android.com/studio/install to download Android Studio.
  4. Use the installer to install Android Studio.
Android App using Android Studio - Android Studio Setup
Android Studio Setup

In “Choose Components”, select “Android Studio” and “Android Virtual Device”

Android App using Android Studio - Android AVD
Install an Android AVD?

Accept the default installation directory “C:\Program Files\Android\Android Studio

Android App using Android Studio - Installation location
Installation location

Follow the on-screen instruction and accept the defaults to complete the installation.

The Next button is enabled when installation completes

Click “Next”

Leave the checkbox checked

1.2 Installing Android SDK

Adding too many SDK packages, especially the so-called system images for emulating different devices, will take an extremely LONG time. They also take up a lot of disk space of your hard disk, a few GBytes per API level !!! For our simple application, we only need a small set of SDK packages.

2. Running Android Studio

Launch Android Studio, since it is the first time, it presents a Complete Installation dialog box that offers the option of importing settings from a previous installation.

Previous settings can be imported

We finally reach to this window:

Android Studio Setup Wizard

Click “Next”:

Choose an installation type
Select UI type

Finally click Finish to complete the wizard. Now the Welcome to Android Studio dialog box appeares.

Welcome to Android Studio

3. Build your first android app

3.1 Start a new project

Click Start a new Android Studio project. Choose Empty Activity from next window.

Choose your project

On the Create New Project window that opens, name your project My First Android Application.

Android App using Android Studio - project configurations
Set the project configurations

You can change the location of the project file if you desire.
Click Finish.

The first time you use Android Studio, it has to download some files related to its constraint layout, which is used to build responsive user interfaces.

After downloading completes, click Finish. Main window of the project will appear:

Android App using Android Studio - Main window
Main window

3.2 The project and main window

3.2.1 Tools menu

From Tools menu you can access to AVD Manager and SDK Manager:

Android App using Android Studio - Tools menu
Tools menu

AVD Manager: It provides a graphical user interface in which you can create and manage Android Virtual Devices (AVDs), which are required by the Android Emulator.
(http://www.androiddocs.com/tools/help/avd-manager.html )

SDK Manager: It is a command line tool that allows you to view, install, update, and uninstall packages for the Android SDK.

3.2.2 Project window

As you can see, Project Window is divided into two main parts:

  • app
  • Gradle Scripts
Project Window

These are the subfolders of app:

  • manifests contains AndroidManifest.xml which describes the structure of an Android app. This file also records permission settings and other details about the app
  • java  contains an app’s Java source files
  • res  contains an app’s resource files:
    • drawable  contains an app’s artwork
    • layout  contains an app’s layout files; activity_main.xml (the main activity’s layout file) is in here.
    • mipmap contains various ic_launcher.png files, which store launcher screen icons of different resolutions.
    • values  contains colors.xmlstrings.xml, and styles.xml.

The Gradle Scripts branch identifies various files that are used by Android Studio’s Gradle-based build system. (.gradle and .properties files)

3.3 Android example app

MainActivity.java class: The activity’s source code is stored in the file MainActivity.java

MainActivity.java

public class MainActivity extends AppCompatActivity {
    AnimationDrawable androidAnimation;

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

The onCreate() method: All of the app’s work takes place in MainActivity‘s overriding onCreate(Bundle)method.

onCreate(Bundle) first invokes its same-named superclass method, a rule that must be followed by all overriding activity methods.
https://www.javaworld.com/article/3104621/android-studio-for-beginners-part-2-explore-and-code-the-app.html

This method then executes setContentView(R.layout.activity_main) to establish the app’s user interface. R.layout.activity_main is an identifier (ID) for an application resource, which resides in a separate file. You interpret this ID as follows:

  • R is the name of a class that’s generated when the app is being built. This class is named R because its content identifies various kinds of application resources, including layouts, images, strings, and colors.
  • layout is the name of a class that’s nested within R. An application resource whose ID is stored in this class describes a specific layout resource. Each kind of application resource is associated with a nested class that’s named in a similar fashion. For example, string identifies string resources.
  • activity_main is the name of an int-based constant declared within layout. This resource ID identifies the main layout resource. Specifically, activity_main refers to a activity_main.xml file that stores the main activity’s layout information. activity_main is MainActivity‘s only layout resource.
activity_main.xml location

So behind the scenes, Android creates the user interface components described in activity_main.xml and positions them on the device screen as specified by activity_main.xml‘s layout data. Now go to your activity_main.xml and paste the code below in it

activity_main.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:background="#ffffff"
    android:gravity="center"
    android:orientation="vertical">

<ImageView
    android:id="@+id/android"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginBottom="10dip" />

    <Button
        android:id="@+id/animate"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/animate" />
</LinearLayout>

The screen is based on views (abstractions of user interface components) and  Android refers to specific views (such as buttons or spinners) as widgets.

Different Views

As you can see a LinearLayout element is declared.

LinearLayout is a view group that aligns all children in a single direction, vertically or horizontally. You can specify the layout direction with the android:orientation attribute.

The <LinearLayout> tag specifies several attributes for controlling the layout:

  • orientation identifies the linear layout as horizontal or vertical. Contained widgets are laid out horizontally or vertically. ("horizontal" and "vertical")
  • layout_width identifies the width of the layout. Legal values:
    • "fill_parent" to be as wide as the parent.
      (Note that fill_parent was renamed to match_parent in Android 2.2, but is still supported and widely used.)
    • "wrap_content" to be wide enough to enclose content.
  • layout_height identifies the height of the layout. Legal values:
    • "fill_parent" to be as tall as the parent
    • "wrap_content" to be tall enough to enclose content
  • gravity identifies how the layout is positioned relative to the screen. For example, "center" specifies that the layout should be centered horizontally and vertically on the screen.
  • background identifies a background image, a gradient, or a solid color. For example, (#ffffff) is a hexadecimal color identifier which signifies a solid white background .
LinearLayout orientation

As you see Android can not resolve symbol @string/animate. We will declare it later in strings.xml

Cannot resolve symbol ‘@string/animate’

ImageView and Button elements specifies an id attribute, which identifies the element so that it can be referenced from code. The resource identifier (special syntax that begins with @) assigned to this attribute begins with the @+id prefix. For example, @+id/android identifies the ImageView element as android; this element is referenced from code by specifying R.id.android.
https://www.javaworld.com/article/3104621/android-studio-for-beginners-part-2-explore-and-code-the-app.html

ImageView specifies a layout_marginBottom attribute to identify a space separator between itself and the button that follows vertically.

3.3.1 Coding the strings.xml

strings.xml stores string data that is referenced from other locations. For example in the activity_main.xml file the <Button> tag includes an android:text="@string/animate" attribute. This attribute references the button’s text via @string/animate, which references a string resource named animate that’s stored in strings.xml.

strings.xml location

strings.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="app_name">My Application</string>
    <string name="animate">Animate</string>
</resources>

3.3.2 Coding the animate.xml

Create a file named android_animate.xml in drawable folder.

Right click on drawable –> New –> File

create a new .xml file under drawable folder

Now select drawable as a destination directory:

Destination directory

Choose a name for the file:

Type the name of new file

android_animate.xml stores an animation list of drawable items.

android_animate.xml

<animation-list xmlns:android="http://schemas.android.com/apk/res/android"
    android:oneshot="true">
    <item android:drawable="@drawable/image0" android:duration="300" />
    <item android:drawable="@drawable/image01" android:duration="300" />
    <item android:drawable="@drawable/image02" android:duration="300" />
    <item android:drawable="@drawable/image0" android:duration="300" />
</animation-list>

As you see there are some symbols that can not be resolved:

android_animate.xml

It is because the images related to them do not exist in drawable folder.
The @drawable/androidx resource reference (where xranges from 0 through 2) identifies an image file whose name starts with android.
Inorder to solve this problem, copy the android0.pngandroid1.png, and android2.png files (referenced in Listing 4) from the source code associated with this article to the drawable branch. Assuming you’re working in Windows, select these files from Windows Explorer and paste them into the android_animate.xml branch (right-click the branch name and select Paste).

animation-list element describes the drawable sequence. This element’s oneshot attribute determines if the animation will cycle in a loop or occur only once.

Inside the animation-list element is a sequence of item elements. Each item element identifies one drawable via its drawable attribute. The duration attribute identifies the number of milliseconds that must elapse before the next item element’s drawable is displayed.

Now we get back to our MainActivity.java file, we can now add these lines to onCreate(Bundle) method:

MainActivity.java

ImageView androidImage = (ImageView) findViewById(R.id.android);
androidImage.setBackgroundResource(R.drawable.android_animate);
androidAnimation = (AnimationDrawable) androidImage.getBackground();
final Button btnAnimate = (Button) findViewById(R.id.animate);
View.OnClickListener ocl;
ocl = new View.OnClickListener()
{
  @Override
  public void onClick(View v)
  {
    androidAnimation.stop();
    androidAnimation.start();
  }
};
btnAnimate.setOnClickListener(ocl);

ImageView androidImage = (ImageView) findViewById(R.id.android); This statement first calls View‘s View findViewById(int id) method to find the android.widget.ImageView element declared in main.xml and identified as android.

androidImage.setBackgroundResource(R.drawable.android_animate); This statement sets the view’s background to the resource identified by R.drawable.android_animate. The R.drawable.android_animateargument identifies android_animate.xml. The setBackgroundResource() call links the androidImage view to the sequence of images described by android_animate.xml, which will be drawn on this view.

ImageView lets an app animate a sequence of drawables by calling AnimationDrawable methods. Before the app can do this, it must obtain ImageView‘s AnimationDrawable. The androidAnimation = (AnimationDrawable) androidImage.getBackground(); assignment accomplishes this task. The AnimationDrawable instance is used to start and stop an animation.

Finally, onCreate(Bundle) creates the Animate button and obtains its information from main.xml.

It then uses onClickListener interface to create a listener object. This object’s void onClick(View v) method is invoked whenever the user clicks the button.

To stop, then start the animation, Animate‘s click listener invokes androidAnimation.stop(); followed by androidAnimation.start();

3.3.3 Building your Android app

Build menu –> Select Make Project. You should observe a Gradle Build Running message on the status bar. After a little while, you should observe a Gradle Build Finished message.

3.3.4 Running your Android app on an emulated device

In this section I’ll show you how to run an Android application on an emulated device.

Run menu –> Select Run ‘app’  Also you can click the green triangle button on the toolbar. Now Android Studio responds with the Select Deployment Target dialog box.

Select Deployment Target dialog

After you’ve initialized the Android Debug Bridge, a list of all connected USB devices and running emulators that have been detected by Android Studio will be displayed.

List of connected devices

As you see Android Studio hasn’t detected any connected USB devices or emulators. Click Create New Virtual Device.

Choose any type of device you want for your application

I selected Nexus 5X. In next page download any system image you wish.

You can keep the defaults settings, then click Finish. Now the Select Deployment Target dialog box displays again:

Nexus 5X API 15 is available

Click OK.

Now Run the app. The first image named image0 is displayed on the screen and below it there is the button named Animate. Clicking on the button causes the image to change!!!

First image
Second image
Third image

4. Download the Complete Source Code

This was a tutorial of Build your First Android App using Android Studio.

Download
You can download the full source code of this example here: Build your First Android App using Android Studio

Firouzeh hejazi

A self-motivated and hard-working developer with more than 4 years of extensive experience in developing software in java platforms. A multi-skilled and problem-solving engineer who has participated in implementing a range of applications in different roles. Possess a MSc in Knowledge Engineering and Decision Science.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Back to top button