Beginning with Android Development

Anurag Bansal
MDG Space
Published in
12 min readJan 13, 2021

--

Downloading Android Studio

  1. Check out the whole procedure for downloading at https://developer.android.com/studio/install.

If you are not able to Install Android Studio with these Instructions, contact us at https://mdg.iitr.ac.in/.

Steps for Cloning Github Repository

Steps if you haven’t installed Git:

Mac OS

Open your terminal and install Git using Homebrew:

  • /bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"
  • $ brew install git

Verify the installation was successful by typing which git --version:

  • $ git --version

Configure your git username and email using the following commands, replacing "your-username" name with your own. These details will be associated with any commits that you create:

  • $ git config --global user.name "your-username" $ git config --global user.email "your-email"

Windows

  1. Download the latest Git for Windows installer.
  2. When you’ve successfully started the installer, you should see the Git Setup wizard screen. Follow the Next and Finish prompts to complete the installation. The default options are pretty sensible for most users.
  3. Open a Command Prompt (or Git Bash if during installation you elected not to use Git from the Windows Command Prompt).
  4. Run the following commands to configure your git username and email using the following commands, replacing "your-username" name with your own. These details will be associated with any commits that you create:
  • $ git config --global user.name "your-username" $ git config --global user.email "your-email"

Linux

Debian / Ubuntu (apt-get)

From your shell, install Git using apt-get:

  • $ sudo apt-get update
  • $ sudo apt-get install git

Verify the installation was successful by typing git --version:

  • $ git --version

Configure your git username and email using the following commands, replacing "your-username" name with your own. These details will be associated with any commits that you create:

  • $ git config --global user.name "your-username" $ git config --global user.email "your-email"

Fedora (dnf/yum)

Git packages are available via both yum and dnf:

From your shell, install Git using dnf (or yum, on older versions of Fedora)

  • $ sudo dnf install git

or

  • $ sudo yum install git

Verify the installation was successful by typing git --version:

  • $ git --version

Configure your git username and email using the following commands, replacing "your-username" name with your own. These details will be associated with any commits that you create:

  • $ git config --global user.name "your-username" $ git config --global user.email "your-email"

Steps for Cloning Git:

  • $ git clone "url of repo"

You can find the URL from the repo as highlighted in the image below:

Basics of Android Studio

  1. The toolbar lets you carry out a wide range of actions, including running your app and launching Android tools.
  2. The navigation bar helps you navigate through your project and open files for editing. It provides a more compact view of the structure visible in the Project window.
  3. The editor window is where you create and modify code. Depending on the current file type, the editor can change. For example, when viewing a layout file, the editor displays the Layout Editor.
  4. The tool window bar runs around the outside of the IDE window and contains the buttons that allow you to expand or collapse individual tool windows.
  5. The tool windows give you access to specific tasks like project management, search, version control, and more. You can expand them and collapse them.
  6. The status bar displays the status of your project and the IDE itself, as well as any warnings or messages.

Project Structure

Application Directory Structure

Each project in Android Studio contains one or more modules with source code files and resource files. Types of modules include:

  • Android app modules
  • Library modules
  • Google App Engine modules

By default, Android Studio displays your project files in the Android project view, as shown in figure 1. This view is organized by modules to provide quick access to your project’s key source files.

All the build files are visible at the top level under Gradle Scripts, and each app module contains the following folders:

  • manifests: Contains the AndroidManifest.xml file.
  • Java: Contains the Java source code files, including JUnit test code.
  • res: Contains all non-code resources, such as XML layouts, UI strings, and bitmap images.

The Android project structure on disk differs from this flattened representation. To see the actual file structure of the project, select Project from the Project dropdown (in the figure, it’s showing as Android).

Terminology

Views/Layouts

A layout defines the structure for a user interface in your app, such as in an activity. All elements in the layout are built using a hierarchy of View and ViewGroup objects. A View usually draws something the user can see and interact with. Whereas a ViewGroup is an invisible container that defines the layout structure for View and other ViewGroup objects, as shown in the figure.

The Views inside a ViewGroup/Layoutare also called the children of the ViewGroup/Layout .

The View objects are usually called "widgets" and can be one of many subclasses, such as Button or TextView. The ViewGroup objects are usually called "layouts" can be one of many types that provide a different layout structure, such as LinearLayout or ConstraintLayout .

You can declare a layout in two ways:

  • Declare UI elements in XML. Android provides a straightforward XML vocabulary that corresponds to the View classes and subclasses, such as those for widgets and layouts. You can also use Android Studio’s Layout Editor to build your XML layout using a drag-and-drop interface.
  • Instantiate layout elements at runtime. Your app can create View and ViewGroup objects (and manipulate their properties) programmatically.

Declaring your UI in XML allows you to separate the presentation of your app from the code that controls its behavior. Using XML files also makes it easy to provide different layouts for different screen sizes and orientations (discussed further in Supporting Different Screen Sizes).

Writing XML Files

Using Android’s XML vocabulary, you can quickly design UI layouts and the screen elements they contain, in the same way you create web pages in HTML — with a series of nested elements.

Each layout file must contain exactly one root element, which must be a View or ViewGroup object. Once you’ve defined the root element, you can add additional layout objects or widgets as child elements to gradually build a View hierarchy that defines your layout. For example, here’s an XML layout that uses a vertical LinearLayout to hold a TextView and a Button:

<?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:id="@+id/text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello, I am a TextView" />
<Button android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello, I am a Button" />
</LinearLayout>

After you’ve declared your layout in XML, save the file with the .xml extension, in your Android project's res/layout/ directory, so it will properly compile.

More information about the syntax for a layout XML file is available in the Layout Resources document.

Loading XML Files

public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_layout);
}

The line setContentView(R.layout.main_layout) links your XML file (main_layout) with the Activity .

The XML file main_layout is stored in the res/layout/ directory.

Activities are basically the classes that are triggered by the Android OS at the runtime of your app.

Attributes

Every View and ViewGroup object supports its own variety of XML attributes. Some attributes are specific to a View object (for example, TextView supports the textSize attribute).

Attributes can basically be thought of as properties for the View Objects defined in the Android Framework and are synonymous with the object attributes in Object-Oriented Programming.

<TextView android:id="@+id/text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello, I am a TextView" />

For example, in the above code textis an attribute of TextView defined in the XML file.

Attributes like id are common to all views and are used for identifying views defined in the XML files.

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

Like for Button in the above example,

Button myButton = (Button) findViewById(R.id.my_button);

the above piece of code is used for accessing it in your Activity.

Android View Groups

Linear Layout

  • Aligns the children views either horizontally or vertically.
  • The attribute android:orientation specifies whether to horizontally or vertically align children views.
  • We usually use the attribute android:weight in the children views/viewgroups to decide what percentage of the available space they should occupy.
  • An attribute android:weightSum defines the maximum weight sum, and is calculated as the sum of the layout_weight of all the children if not specified explicitly.

TRIVIA: What would happen if the weightSum is less than the sum of weights given to children explicitly?

Relative Layout

  • Relative Layout enables you to specify how child views are positioned relative to each other.
  • The position of each view can be specified as relative to sibling elements or relative to the parent.

Some common attribute usages in the relative layout:
Difference between android:layout_alignRight and android:layout_toRightOf : android:layout_alignRight is used to align a view’s rightmost edge to the rightmost edge of the specified view, whereas android:layout_toRightOf is used to place a view to the right of the specified view, i.e., the left edge of a view is positioned to the right of the specified view.

Why prefer android:layout_toEndOf instead of android:layout_toRightOf:
The views have LTR(left-to-right) orientation by default, i.e., they start from left and end towards their right, but this orientation can be changed to RTL(right-to-left), where views start from the right and end towards left. In such cases, the views with the attribute android:layout_toEndOf will correctly align to the end w.r.t the view specified, whereas android:layout_toRightOfwill still align it towards the right.

  • Read more about Relative Layout here and here.

TRIVIA: Relative Layout measures a view twice, whereas Linear Layout measures only once (if weights are not used)!
Sources: Stack Overflow and Medium

Constraint Layout

  • Constraint Layout is a new ViewGroup for android. The main motive of constraint layout is to design layouts that are flexible and look the same in all screen sizes.
  • The layout editor uses constraints to identify the position of a view on the screen.
  • The attributes like android:layout_constraintTop_toTopOf, android:layout_constraintTop_toBottomOfand other similar attributes are used to set constraints to views w.r.t. other views.
  • It supports chaining of views, using which the views can be easily positioned over a space, and works much better than using a combo of weights and gravity to achieve a configuration. The attributes android:layout_constraintHorizontal_chainStyle and android:layout_constraintVertical_chainStyle can be supplied with various values to produce the following effects:

Supports horizontal and vertical bias, by which we can tweak the positioning to favor one side over another using the bias attributes.

Usage:

<android.support.constraint.ConstraintLayout ...>
<Button android:id="@+id/button" ...
app:layout_constraintHorizontal_bias="0.3"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent/>

The above code produces a button like:

  • It also provides a view called Guideline using which you can have an imaginary line (which is not a view) anywhere on the screen and position views according to it. You can position this guideline by providing it either a fixed value or a percentage value (w.r.t. the screen).

Basic Android Views

Text View

A user interface element that displays text to the user.

Usage:

<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="@+id/text_view_id"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:text="@string/hello" />
</LinearLayout>

Some Attributes:

android:widthMakes the TextView be exactly this wide.

android:heightMakes the TextView be exactly this tall.

android:gravitySpecifies how to align the text by the view's x- and/or y-axis when the text is smaller than the view.

android:textSize: Size of the text.

android:textStyle Style (normal, bold, italic, bold|italic) for the text.

android:textText to display.

android:textColorText color.

android:textAlignment Align the Text.

Image View

Displays image resources, for example, Bitmap or Drawable resources. ImageView is also commonly used to apply tints to an image and handle image scaling.

Usage:

<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/my_image"
android:contentDescription="@string/my_image_description"
/>
</LinearLayout>

To learn more about Drawables, see Drawable Resources. To learn more about working with Bitmaps, see Handling Bitmaps.

Some Attributes:

android:maxHeightAn optional argument to supply a maximum height for this view.

android:maxWidthAn optional argument to supply a maximum width for this view.

android:scaleTypeControls how the image should be resized or moved to match the size of this ImageView.

android:srcSets a drawable as the content of this ImageView.

android:tintThe tinting color for the image.

android:tintModeBlending mode used to apply the image tint.

Button View

A user interface element the user can tap or click to perform an action.

<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<Button
android:id="@+id/button_id"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:text="@string/self_destruct"
/>
</LinearLayout>

Some Attributes:

android:minHeightDefines the minimum height of the view.

android:minWidthDefines the minimum width of the view.

android:onClickName of the method in this View's context to invoke when the view is clicked.

android:backgroundA drawable to use as the background.

Some general trivia

Padding and Margin:

  • android:padding attribute adjusts the position of a view’s content from its borders internally.
  • android:margin the attribute changes the distance of the borders of a view from its parent/view on which it depends.

Gravity and LayoutGravity:

  • android:layout_gravity the attribute is used to provide gravity (positioning w.r.t parent) to the entire view box.
  • android:gravity the attribute is used to provide gravity to a view’s contents so that it is positioned accordingly within the view box.

Baseline:

  • In RelativeLayout, if you add layout_alignBaseline to a textView, the text in that view will scoot to align with the baseline of the specified element. The text from both elements will appear as if it were written on the same invisible line.
  • Have a look at an example here

Accessing Views from Java Files:

Text View:

public class MainActivity extends Activity {

protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final TextView helloTextView = (TextView) findViewById(R.id.text_view_id);
helloTextView.setText(R.string.user_greeting);
}
}

Image View:

public class MainActivity extends Activity {

protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final ImageView myImageView = (ImageView) findViewById(R.id.image_view_id);
myImageView.setImageDrawable(R.drawable.myImage)
}
}

Button View:

public class MyActivity extends Activity {
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);

setContentView(R.layout.content_layout_id);

final Button button = findViewById(R.id.button_id);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Code here executes on main thread after user presses button
}
});
}
}

Brief Note on Gradle

Android Studio uses Gradle, an advanced build toolkit, to automate and manage the build process while allowing you to define flexible custom build configurations. Each build configuration can define its own set of code and resources while reusing the parts common to all versions of your app. The Android plugin for Gradle works with the build toolkit to provide processes and configurable settings that are specific to building and testing Android applications.

Gradle and the Android plugin help you configure the following aspects of your build:

Build types: Build types define certain properties that Gradle uses when building and packaging your app and are typically configured for different stages of your development lifecycle. For example, the debug build type enables debug options and signs the APK with the debug key, while the release build type may shrink, obfuscate, and sign your APK with a release key for distribution. You must define at least one build type in order to build your app — Android Studio creates the debug and release build types by default. To start customizing packaging settings for your app, learn how to Configure build types.

The top-level build file: The top-level build.gradle file, located in the root project directory, defines build configurations that apply to all modules in your project. By default, the top-level build file uses the buildscript block to define the Gradle repositories and dependencies that are common to all modules in the project. The following code sample describes the default settings and DSL elements you can find in the top-level build.gradle after creating a new project

The module-level build file: The module-level build.gradle file, located in each project/module/ directory, allows you to configure build settings for the specific module it is located in. Configuring these build settings allows you to provide custom packaging options, such as additional build types and product flavors, and override settings in the main/ app manifest or top-level build.gradle file.

Conclusion

For detailed code, https://github.com/mdg-iitr-learning/Counter.

We hope you enjoyed the Tutorial. 😄 🎉

--

--