Android Studio,Explore and code the app
Write your first animated Android app with Android Studio’s Project editor
In Part 1 of this amateur’s advent to Android Studio, you installation Android Studio to your development environment and got to recognise the user interface. Now, in Part 2, you may code your first app.
The lively cellular app consists of a single interest, which presents Google’s Android robot individual and a button for animating the character. Clicking the button causes the man or woman to step by step change coloration from green to red to blue, then again to green. While the app is not especially useful, writing it’ll help you get at ease with the use of Android Studio. In Part three, you’ll build and run the app the use of an Android tool emulator and a Kindle Fire pill.
Note that this series has been up to date for Android Studio three.2.1, the contemporary solid release as of this writing.
Android Studio’s Project and editor windows
I delivered Android Studio’s essential window on the cease of Part 1. This window is divided into several regions, along with a Project window where you pick out an app’s useful resource documents, and various editor windows wherein you’ll write the code and specify assets for mobile apps in Android Studio. The Project window and an editor window are shown in Figure 1.
The Project window highlights W2A, that’s the call of the app’s W2A.Java supply document (despite the fact that the .Java report extension isn’t always proven). Corresponding to W2A is an editor window, reached with the aid of double-clicking W2A inside the Project window. The editor window famous the file’s modern-day contents, in this situation the skeletal Java source code for the app’s essential interest.
Each editor window is associated with a tab. For instance, W2A’s editor window is associated with a W2A.Java tab. A 2d tab identified as important.Xml (the default XML-based layout for the app’s principal activity) is likewise proven. You circulate from one editor window to some other through clicking the window’s tab.
Android Studio,The example app
The example app (W2A.Java) consists of a major interest that displays the Android robotic man or woman and a button. When the person presses the button, the robot animates through a chain of colours. In this section, we’ll discover the pastime’s source code and assets.
Explore and code the Android example app
The hobby’s source code is saved within the record W2A.Java, presented in Listing 1.
Android Studio,Listing 1. W2A.java
package ca.javajeff.w2a; import android.app.Activity; import android.graphics.drawable.AnimationDrawable; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.ImageView; public class W2A extends Activity { AnimationDrawable androidAnimation; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); 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); } }
The W2A.Java report starts offevolved with a package deal announcement, which names the bundle (ca.Javajeff.W2a) that stores the W2A class. Next, the code describes the W2A elegance, which extends android.App.Activity.
W2A first proclaims an androidAnimation instance subject of kind android.Pictures.Drawable.AnimationDrawable. Objects of kind AnimationDrawable describe body-by way of-frame animations, wherein the modern-day drawable is changed with the next drawable inside the animation series.
What is a drawable? |
A drawable is some thing that may be drawn, consisting of an photograph. AnimationDrawable not directly extends the abstract android.Photos.Drawable.Drawable class, that’s a popular abstraction for a drawable. |
Android Studio,The onCreate() method
All of the app’s work takes region in W2A’s overriding onCreate(Bundle) method: no different methods are required, which facilitates to preserve this app simple.
OnCreate(Bundle) first invokes its equal-named superclass approach, a rule that have to be observed with the aid of all overriding pastime methods.
This technique then executes setContentView(R.Layout.Main) to establish the app’s person interface. R.Layout.Foremost is an identifier (ID) for an utility useful resource, which is living in a separate report. You interpret this ID as follows:
- R is the call of a category it really is generated whilst the app is being built. This elegance is named R due to the fact its content identifies diverse kinds of utility assets, which includes layouts, snap shots, strings, and colorations.
- Format is the name of a class it’s nested inside R. An software resource whose ID is saved in this magnificence describes a selected layout resource. Each type of software aid is associated with a nested class it is named in a comparable style. For example, string identifies string assets.
- Major is the call of an int-based totally consistent declared within layout. This useful resource ID identifies the principle format aid. Specifically, main refers to a primary.Xml report that stores the principle hobby’s format statistics. Principal is W2A’s only format useful resource.
The onCreate() method
Passing R.Layout.Principal to Activity’s void setContentView(int layoutResID) approach instructs Android to create a user interface display using the layout facts saved in foremost.Xml. Behind the scenes, Android creates the user interface components described in primary.Xml and positions them on the device display screen as distinct by way of predominant.Xml’s layout statistics.
The display is based totally on perspectives (abstractions of user interface additives) and think about organizations (perspectives that organization associated consumer interface additives). Views are times of training that subclass the android.View.View magnificence and are analogous to AWT/Swing components. View groups are times of classes that subclass the summary android.View.ViewGroup class and are analogous to AWT/Swing boxes. Android refers to unique views (consisting of buttons or spinners) as widgets.
Continuing, onCreate(Bundle) executes ImageView androidImage = (ImageView) findViewById(R.Identification.Android);. This statement first calls View’s View findViewById(int identity) approach to find the android.Widget.ImageView element declared in major.Xml and diagnosed as android. It instantiates ImageView and initializes it to the values declared inside the major.Xml report. The declaration then saves this item’s reference in nearby variable androidImage.
Android Studio,ImageView and AnimationDrawable
Next, the androidImage.SetBackgroundResource(R.Drawable.Android_animate); announcement invokes ImageView’s inherited (from View) void setBackgroundResource(int resID) approach, putting the view’s history to the useful resource recognized with the aid of resID. The R.Drawable.Android_animate argument identifies an XML report named android_animate.Xml (provided later), which stores facts at the animation, and that is saved in res’s drawable subdirectory. The setBackgroundResource() call links the androidImage view to the series of pics described by using android_animate.Xml, so as to be drawn on this view. The preliminary photograph is drawn as a result of this approach name.
ImageView we could an app animate a sequence of drawables through calling AnimationDrawable strategies. Before the app can do this, it have to acquire ImageView’s AnimationDrawable. The androidAnimation = (AnimationDrawable) androidImage.GetBackground(); assignment announcement that follows accomplishes this task by invoking ImageView’s inherited (from View) Drawable getBackground() method. This method returns the AnimationDrawable for the given ImageView, that is eventually assigned to the androidAnimation subject. The AnimationDrawable example is used to start and prevent an animation, a system I’ll describe rapidly.
Finally, onCreate(Bundle) creates the Animate button. It invokes findByViewId(int) to obtain the button information from important.Xml, then instantiates the android.Widget.Button magnificence.
It then employs the View magnificence’s nested onClickListener interface to create a listener item. This object’s void onClick(View v) technique is invoked on every occasion the user clicks the button. The listener is registered with its Button object with the aid of calling View’s void setOnClickListener(AdapterView.OnClickListener listener) technique.
To forestall, then start the animation, Animate’s click listener invokes androidAnimation.Prevent(); followed through androidAnimation.Start();. The stop() method is known as earlier than begin() to ensure that a next click of the Animate button causes a brand new animation to begin.
Android Studio,Update and save your code
Before we keep, update the skeletal code to your W2A.Java tab with the code from Listing 1. Save the contents of this window with the aid of pressing Ctrl+S, or choose Save All from the File menu.
Coding the Android app’s main.xml
The app’s essential activity is related to an XML-based format, which is saved in file foremost.Xml, and that is presented in Listing 2.
Android Studio,Listing 2. main.xml
After the XML announcement, Listing 2 pronounces a LinearLayout detail that specifies a layout (a view organization that arranges contained perspectives on an Android tool’s display screen in some way) for arranging contained widgets (together with nested layouts) either horizontally or vertically across the display screen.
The tag specifies several attributes for controlling this linear format. These attributes consist of the following:
- orientation identifies the linear format as horizontal or vertical. Contained widgets are laid out horizontally or vertically, and the default orientation is horizontal. “horizontal” and “vertical” are the only criminal values that may be assigned to this attribute.
- Layout_width identifies the width of the layout. Legal values include “fill_parent” (to be as huge because the parent) and “wrap_content” (to be extensive sufficient to surround content material). (Note that fill_parent became renamed to match_parent in Android 2.2, however is still supported and extensively used.)
- layout_height identifies the peak of the layout. Legal values consist of “fill_parent” (to be as tall because the parent) and “wrap_content” (to be tall sufficient to surround content).
- Gravity identifies how the layout is located relative to the display screen. For instance, “center” specifies that the format ought to be centered horizontally and vertically on the screen.
- Heritage identifies a historical past image, a gradient, or a stable color. For simplicity, I’ve hardcoded a hexadecimal colour identifier to suggest a stable white historical past (#ffffff).
Android app’s main.xml
The LinearLayout element encapsulates ImageView and Button factors. Each of those elements specifies an identification attribute, which identifies the element so that it can be referenced from code. The useful resource identifier (unique syntax that starts offevolved with @) assigned to this characteristic begins with the @+id prefix. For example, @+identification/android identifies the ImageView element as android; this detail is referenced from code through specifying R.Id.Android.
These elements additionally specify layout_width and layout_height attributes for determining how their content is laid out. Each attribute is assigned wrap_content in order that the element will seem at its natural length.
ImageView specifies a layout_marginBottom characteristic to become aware of a area separator among itself and the button that follows vertically. The area is distinctive as 10 dips, or density-independent pixels. These are digital pixels that apps can use to express format dimensions/positions in a display screen density-unbiased manner.
Density-independent pixels |
A density-unbiased pixel (dip) is equivalent to at least one physical pixel on a 160-dpi display, the baseline density assumed by using Android. At runtime, Android transparently handles any scaling of the specified dip devices, primarily based on the actual density of the screen in use. Dip devices are transformed to display pixels thru the equation: pixels = dips * (density / one hundred sixty). For example, on a 240-dpi screen, 1 dip equals 1.5 physical pixels. Google recommends the usage of dip units to outline your app’s person interface to make certain right display of the person interface on different device screens. |