0% found this document useful (0 votes)
41 views37 pages

Android Emulator Unit2

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
41 views37 pages

Android Emulator Unit2

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 37

UNIT-2

UNIT – II Emulator-Android Virtual Device, Launching emulator, Editing emulator settings, Emulator
shortcuts, Logcat usage, Introduction to DDMS, Second App:- (switching between activities) , Develop an
app for demonstrating the communication between Intents, Basic UI design, Form widgets, Text Fields,
Layouts, [dip, dp, sip,sp] versus px.

Android Emulator- Android Virtual Device

The Android emulator is an Android Virtual Device (AVD), which represents a


specific Android device. We can use the Android emulator as a target device to
execute and test our Android application on our PC. The Android emulator
provides almost all the functionality of a real device. We can get the incoming
phone calls and text messages. It also gives the location of the device and simulates
different network speeds. Android emulator simulates rotation and other hardware
sensors. It accesses the Google Play store, and much more
Testing Android applications on emulator are sometimes faster and easier than
doing on a real device. For example, we can transfer data faster to the emulator
than to a real device connected through USB.

The Android emulator comes with predefined configurations for several Android
phones, Wear OS, tablet, Android TV devices.

Requirement and recommendations

The Android emulator takes additional requirements beyond the basic system
requirement for Android Studio. These requirements are given below:

SDK Tools 26.1.1 or higher


o 64-bit processor
o Windows: CPU with UG (unrestricted guest) support
o HAXM 6.2.1 or later (recommended HAXM 7.2.0 or later)

Install the emulator

The Android emulator is installed while installing the Android Studio. However
some components of emulator may or may not be installed while installing
Android Studio. To install the emulator component, select the Android
Emulator component in the SDK Tools tab of the SDK Manager.

Run an Android app on the Emulator

We can run an Android app form the Android Studio project, or we can run an app
which is installed on the Android Emulator as we run any app on a device.

To start the Android Emulator and run an application in our project:

1. In Android Studio, we need to create an Android Virtual Device (AVD) that


the emulator can use to install and run your app. To create a new AVD:-

1.1 Open the AVD Manager by clicking Tools > AVD Manager.
1.2 Click on Create Virtual Device, at the bottom of the AVD Manager dialog.
Then Select Hardware page appears.
1.3 Select a hardware profile and then click Next. If we don?t see the hardware
profile we want, then we can create or import a hardware profile. The System
Image page appears.

1.4 Select the system image for the particular API level and click Next. This leads
to open a Verify Configuration page.
1.5 Change AVD properties if needed, and then click Finish.

2. In the toolbar, choose the AVD, which we want to run our app from the target
device from the drop-down menu.
3. Click Run.

Launch the Emulator without first running an app

To start the emulator:

1. Open the AVD Manager.


2. Double-click an AVD, or click Run

While the emulator is running, we can run the Android Studio project and select
the emulator as the target device. We can also drag an APKs file to install on an
emulator, and then run them.

Start the emulator from the command line

The Android SDK includes the Android device emulator. Android emulator lets
you develop and test out the application without using a physical device.

Starting the emulator

Using the emulator command, we will start an emulator. It is an alternative to run


our project or start through the AVD Manager.

Here is the basic command-line syntax for starting a virtual device:

1. $ emulator -avd avd_name [ {-option [value]} ... ]

or

1. $ emulator @avd_name [ {-option [value]} ... ]

For example, if we execute the emulator from Android Studio on a Mac, the
default command line will be similar as follows:

1. $ /Users/user_name/Library/Android/sdk/emulator/emulator -avd Nexus_5X_API


_23 -netdelay none -netspeed full

To display the list of AVD names, enter the following command:

1. $ emulator -list-avds
Run and stop an emulator, and clear data

From the Virtual Device page, we can perform the following operation on
emulator:

o To run an Android emulator that uses an AVD, double-click the AVD, or


click Launch
o To stop the running emulator, right-click and select Stop, or click Menu ▼
and select Stop.
o If we want to clear the data from an emulator and return it to the initial state
when it was first defined, then right-click an AVD and select Wipe Data. Or
click menu ▼ and select Wipe Data.

EDITING EMULATOR SETTING:

The Android Emulator can use hardware acceleration features to improve


performance, sometimes drastically. This page describes how you can configure
graphics and virtual machine (VM) acceleration to get higher performance from
the emulator.

Configure graphics acceleration

Graphics acceleration uses your computer's hardware (typically the GPU) to make
screen rendering faster. Android devices use OpenGL for Embedded Systems
(OpenGL ES or GLES) for rendering both 2D and 3D graphics on the screen.

When you create an Android Virtual Device (AVD) in the AVD Manager, you can
specify whether the emulator should use hardware or software to emulate the GPU
of the AVD. Hardware acceleration is recommended and is typically faster.
However, you might need to use software acceleration if your computer uses
graphics drivers that aren't compatible with the emulator.

By default, the emulator decides whether to use hardware or software graphics


acceleration based on your computer setup. If your GPU hardware and drivers are
compatible, the emulator uses the GPU. Otherwise, the emulator uses software
acceleration (using your computer's CPU) to simulate GPU processing.

If you start the emulator from the command line, you can also override the
graphics acceleration setting in the AVD for that virtual device instance.

Requirements

To use graphics acceleration, your development environment must meet the


following requirements:

 SDK Tools: Latest release recommended (version 17 minimum)


 SDK Platform: Latest release recommended (Android 4.0.3, Revision 3, minimum)

Configure graphics acceleration in the AVD Manager

To configure graphics acceleration for an AVD, follow these steps:

1. Open the AVD Manager.


2. Create a new AVD or edit an existing AVD.
3. On the Verify Configuration page, find the Emulated Performance section.
4. Select a value for the Graphics: option.
5. Click Finish.

Configure graphics acceleration from the command line

To specify a graphics acceleration type when you run an AVD from the command
line, include the -gpu option, as shown in the following example:

emulator -avd avd_name -gpu mode [{-option [value]} ... ]

The value of mode can be set to one of the following options:


 auto: Let the emulator choose between hardware or software graphics acceleration
based on your computer setup.
 host: Use the GPU on your computer for hardware acceleration. This option
typically provides the highest graphics quality and performance for the emulator.
However, if your graphics drivers have issues rendering OpenGL, you might need
to use the swiftshader_indirect or angle_indirect options.
 swiftshader_indirect: Use a Quick Boot-compatible variant of SwiftShader to
render graphics using software acceleration. This option is a good alternative
to host mode if your computer can't use hardware acceleration.
 angle_indirect: (Windows only) Use a Quick Boot-compatible variant of ANGLE
Direct3D to render graphics using software acceleration. This option is a good
alternative to host mode if your computer can't use hardware acceleration. In most
cases, ANGLE performance should be similar to using host mode because ANGLE
uses Microsoft DirectX instead of OpenGL. On Windows, Microsoft DirectX
drivers typically have fewer issues than OpenGL drivers. This option uses
Direct3D 11 and requires Windows 10, Windows 8.1, or Windows 7 SP1 with the
Windows 7 Platform Update.
 guest: Use guest-side software rendering. This option provides the lowest graphics
quality and performance for the emulator.

SHORTCUT IN EMULATOR
1. Main Device Keys

Home Home Button


F2 Left Softkey / Menu / Settings button (or Page up)
Shift+f2 Right Softkey / Star button (or Page down)
Esc Back Button
F3 Call/ dial Button
F4 Hang up / end call button
F5 Search Button

2. Other Device Keys

Ctrl+F5 Volume up (or + on numeric keyboard with Num


Lock off)
Volume down (or - on numeric keyboard
Ctrl+F6
with Num Lock off)
F7 Power Button
Camera Button (or Ctrl+5 on numeric keyboard
Ctrl+F3
with Num Lock off)
Switch layout orientation portrait/landscape
Ctrl+F11 backwards (or 7 on numeric keyboard with Num
Lock off)
Switch layout orientation portrait/landscape
Ctrl+F12 forwards (or 9 on on numeric keyboard with Num
Lock off)
F8 Toggle cell network
Toggle code profiling (requires --trace startup
F9
option)
Alt+Enter Toggle full screen mode
F6 Toggle trackball mode
Del Enter trackball mode while key is pressed
DPad left/up/right/down (numeric keypad
4/8/6/2
with Num Lock off)
DPad center click (numeric keypad with Num
5
Lock off)

 LogCat: LogCat usually outputs the messages that we print out using the Log class
accompanied by other system messages. LogCat is integrated to DDMS. We can
filter certain messages when we use LogCat of DDMS and they are:
o Verbose { v (String, String) }
o Info { I (String, String) }
o Debug { d (String, String) }
o Error { e (String, String) }
o Warn { w (String, String) }
 Phone Operations: Using DDMS we can simulate the phone operations like
incoming call or sending SMS, etc. These are:
o Voice
o SMS
 Location: Using DDMS we can also simulate location co-ordinates. We can send
mock location to simulate the actual location coordinates and test the application.
The geo-location flavors of data available to us are:
o Manual
o GPX (GPS exchange file)
o KML (Keyhole Markup Language)

Using LogCats

When we talk about log system of android it is procedure or methodology to


collect and view system debug output. Now, LogCat dumps the log messages. It
includes stack traces or the error messages you intended to receive in case of any
error. We can make use of Log which is a logging class to print out the messages
in the LogCat. Let us discuss some of the common command line options of logcat
and they are:

 -d: It dumps the log to screen and terminates


 -c: It flushes the entire log and then exits.
 -g: It prints the size of log and then terminates.
 -f <name_of_file>: It writes the output of log messages to the <name_of_file>.
Although the default file is sdtout.

Introduction to DDMS
DDMS stands for Dalvik Debug Monitoring Service is basically a graphical user
interface application which is meant for debugging. This application is shipped
with the Android SDK. It provides process examination capabilities, log cat, screen
capture, thread and heap information on device, emulating location information,
emulating incoming call etc. In the tools/ directory DDMS is shipped. DDMS can
function for both connected device and emulator. Although, if you have an
emulator up and running, in that case DDMS would communicated with emulator
by default.
Figure DDMS in tools directory
DDMS usually works as a bridge between integrated development environment
and applications running on device. Now, android application runs on separate
virtual machine. To be more specific every application has its own virtual machine
that’s the simple reason why failure of one application does not hampers the
performance of other application running on same device. So every application has
its own process which runs into a separate a virtual machine. Each process listens
for a debugger but in a different port. For running DDMS we have two ways and
they are as follows:
 Command line: We have to type ddms (./ddms on Linux) from tools/ directory
 Eclipse: In case of Eclipse we have to navigate through the following
path: Window-> Open Perspective->Other.. DDMS

Following snapshot shows path from eclipse as I am running eclipse on windows


operating system and it is as follows:

After DDMS initializes, it connects to adb (android debug bridge) and as soon as a
device is connected, VM monitoring service is created between DDMS and adb.
When VM (virtual machine) on device is started or terminated, it notifies DDMS
about the current status. When VM starts running, DDMS would retrieve the pid
i.e., process ID of VM and it establishes a connection to debugger of VM. These
things are possible as DDMS retrieves the information through adb. The adb
daemon on device helps to open the connection. Thus DDMS can communicate
with VM now.

Facilities provided by DDMS.

 Heap Memory and Threads: DDMS can be used to view the amount of heap
memory used by current process. We can track heap usage at any point of
execution of android application. As far as threads are concerned, DDMS shows
the current threads which are running for our application.

 Tracking objects: DDMS also facilitates the tracking of objects. In other words,
the objects which are allocated to memory and also the threads or classes attached
to the objects respectively. This is very useful when we talk about the performance
of application in terms of memory usage.
 File system: DDMS also provides a file explorer with which we can play around
the file system of attached device (emulator or connected device). We can view,
copy and delete files on device. This is very helpful when we intend to transfer file
from one device to another. This is also useful to keep track of files created by our
application on device.
 Method profiling: DDMS also facilitates method profiling. It is like keeping an
eye on the number of calls to the method, time of execution, etc. In other words,
keeping track of metrics of method.

 Network traffic tool: DDMS includes a Network usage tool which gives a
detailed track of application making network requests. We can easily monitor the
activities of application and can optimize the code as and when required. We can
monitor how frequently the data is being transferred. By keeping track on this, we
can make our application more battery efficient.

 LogCat: LogCat usually outputs the messages that we print out using the Log class
accompanied by other system messages. LogCat is integrated to DDMS. We can
filter certain messages when we use LogCat of DDMS and they are:
o Verbose { v (String, String) }
o Info { I (String, String) }
o Debug { d (String, String) }
o Error { e (String, String) }
o Warn { w (String, String) }
 Phone Operations: Using DDMS we can simulate the phone operations like
incoming call or sending SMS, etc. These are:
o Voice
o SMS
 Location: Using DDMS we can also simulate location co-ordinates. We can send
mock location to simulate the actual location coordinates and test the application.
The geo-location flavors of data available to us are:
o Manual
o GPX (GPS exchange file)
o KML (Keyhole Markup Language)

Using LogCats

When we talk about log system of android it is procedure or methodology to


collect and view system debug output. Now, LogCat dumps the log messages. It
includes stack traces or the error messages you intended to receive in case of any
err or. We can make use of Log which is a logging class to print out the messages
in the LogCat. Let us discuss some of the common command line options of logcat
and they are:

 -d: It dumps the log to screen and terminates


 -c: It flushes the entire log and then exits.
 -g: It prints the size of log and then terminates.
 -f <name_of_file>: It writes the output of log messages to the <name_of_file>.
Although the default file is sdtout.

Four panels of DDMS


We have four panels which provide various debugging data using DDMS and they
are as follows:

1. Devices: This displays the connected devices. It includes real devices and
emulators as well.
2. Emulator Control: Various controls for injecting events and data into the
emulator is possible. It includes Telephony status, Telephony Action and Location
Control. Telephony status specifies the voice and data format, latency and network
speed. With Telephony Action we can make false calls or send SMS. Even the
message content in SMS can be specified. With Location Control it is possible to
send fake GPS signal to the GPS (Global Positioning System) provider in the
emulator.
3. Device Status Panel: This is used to analyze the process. It includes Thread,
Heap, Allocation Tracker, and File Explorer.

4. Bottom Panel: This includes LogCat, Outline, and Properties.

Logcat

Android Studio has a logcat tab inside Android Monitor that prints system events,
such as when a garbage collection occurs, as well as messages your app prints with
the Log class, to assist with debugging. Logcat displays messages in real time and
also keeps a history so you can view older messages.

Log Log Level Description


Log.v(tag, message) Verbose Show all log messages (the default).

Log.d(tag, message) Debug Show debug log messages that are useful during developm

Show expected log messages for regular usage,


Log.i(tag, message) Information as well as the message levels lower in this list.

Log.w(tag, message) Warning Show possible ...

Accessing logcat from the command line

3. If more than one device is attached, then the device must be identified. For
example, adb -d logcat shows the log of the only physical device connected,
while adb -e logcat shows the log of the only emulator running.
4.

Switching between Activities in Android


When making your Android apps you may get to the point where you need to
create multiple Activities for different screens within your app. When you have
multiple Activities you will need a way to transition between them in a way that
doesn’t break the back button functionality.

In order to switch between Activities in Android you will need to follow these
steps:

1. Create the Activities


2. Add the Activities to the app’s Manifest
3. Create an Intent referencing the Activity class you want to switch to
4. Call the startActivity(Intent) method to switch to the Activity
5. Create a back button on the new Activity and call the finish() method on an
Activity when the back button is pressed
Transitioning Between Activities in Android

Create Two Activities


We will start by creating two Activities, FirstActivity and SecondActivity.

The FirstActivity will contain a ConstraintLayout with a TextView label showing


“First Activity” and a Button with the text “Go to Second Activity”.
User Interface of the First Activity

The SecondActivity will contain a ConstraintLayout with a TextView label


showing “Second Activity” and a Button with the text “Back to First Activity”.

Add Both Activities to the App Manifest


Ensure there is an activity entry for both Activities in the application section of the
manifest file located at app/src/main/AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>


<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.learntodroid.switchingbetweenactivities">
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".SecondActivity"></activity>
<activity android:name=".FirstActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
Making the following changes to the FirstActivity class.

Add a new method called “switchActivities()”, inside this method we will create an
Intent passing a parameters of the current activity and the new activity class. Then
use the startActivity(Intent) method to passing the Intent that was just created.

Inside the onCreate method, add an OnClickListener to the Button used for
switching the new Activity. When selected call the switchActivities() method.

public class FirstActivity extends AppCompatActivity {


Button switchToSecondActivity;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_first);
switchToSecondActivity = findViewById(R.id.activity_first_button);
switchToSecondActivity.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
switchActivities();
}
});
}
private void switchActivities() {
Intent switchActivityIntent = new Intent(this, SecondActivity.class);
startActivity(switchActivityIntent);
}

}
Using the finish() method to preserve the back button functionality
Making the following changes to the Second Activity class.

Inside the onCreate method, add an OnClickListener to the Button used for going
back to the previous Activity. When selected call the finish() method will will
remove the Second Activity and take you back to the First Activity.
User Interface of the Second Activity

public class SecondActivity extends AppCompatActivity {

Button backButton;
@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_second);

backButton = findViewById(R.id.activity_second_button);
backButton.setOnClickListener(new View.OnClickListener() {

@Override

public void onClick(View view) {

finish();
}

});

}}

UI screen components

A typical user interface of an android application consists of action bar and the
application content area.

 Main Action Bar


 View Control
 Content Area
 Split Action Bar
These components have also been shown in the image below −

Understanding Screen Components

The basic unit of android application is the activity. A UI is defined in an xml file.
During compilation, each element in the XML is compiled into equivalent Android
GUI class with attributes represented by methods.

View and ViewGroups

An activity is consist of views. A view is just a widget that appears on the screen. It
could be button e.t.c. One or more views can be grouped together into one GroupView.
Example of ViewGroup includes layouts.
Android Layout Design Tutorial: Views

A View is considered as a basic building block for a proper user interface that is
actually created from the View class. This occupies a rectangular area on the screen and
is eventually takes care of drawing and event handling.

A View is the base class for widgets, which are used to create interactive UI
components like buttons, text fields, etc. Now talking about the rectangle area or a box,
It can either be an image, a piece of text, a button or anything that an android
application can display. The rectangle here is actually invisible, but every view
occupies a rectangle shape.

Now let’s point out the major differences between View and the ViewGroup.
View

1. View objects are the basic building blocks of the UI elements in Android.
2. A View is a simple rectangle box which response to the user’s actions.
3. View refers to the android.view. View class, which is the base class of all UI
classes.
4. Examples are EditText, Button, CheckBox, etc..

ViewGroup

1. ViewGroup is the invisible container which holds View and ViewGroup.


2. ViewGroup is the base class for the Layouts.
3. For example, LinearLayout is the ViewGroup that contains Button(View), and
other Layouts also.

Android Layout Design Tutorial: Types of Layouts

A layout defines the structure for a User Interface in the application. All elements in
the layout are built using a hierarchy of View and ViewGroup objects.

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.
 Note: You can also use Android Studio’s Layout Editor to build your XML layout
using a drag-and-drop interface.

 Instantiate layout elements at run time. The application can


create View and ViewGroup objects and manipulate their properties
programmatically.

Types of layout

There are many types of layout. Some of which are listed below −

 Linear Layout
 Absolute Layout
 Table Layout
 Frame Layout
 Relative Layout

Linear Layout

Linear layout is further divided into horizontal and vertical layout. It means it can
arrange views in a single column or in a single row. Here is the code of linear
layout(vertical) that includes a text view.
<?xml version=”1.0” encoding=”utf-8”?>
<LinearLayout xmlns:android=”http://schemas.android.com/apk/res/android”
android:layout_width=”fill_parent”
android:layout_height=”fill_parent”
android:orientation=”vertical” >
<TextView
android:layout_width=”fill_parent”
android:layout_height=”wrap_content”
android:text=”@string/hello” />
</LinearLayout>

AbsoluteLayout

The AbsoluteLayout enables you to specify the exact location of its children. It can be
declared like this.
<AbsoluteLayout
android:layout_width=”fill_parent”
android:layout_height=”fill_parent”
xmlns:android=”http://schemas.android.com/apk/res/android” >
<Button
android:layout_width=”188dp”
android:layout_height=”wrap_content”
android:text=”Button”
android:layout_x=”126px”
android:layout_y=”361px” />
</AbsoluteLayout>

TableLayout
The TableLayout groups views into rows and columns. It can be declared like this.
<TableLayout
xmlns:android=”http://schemas.android.com/apk/res/android”
android:layout_height=”fill_parent”
android:layout_width=”fill_parent” >
<TableRow>
<TextView
android:text=”User Name:”
android:width =”120dp”
/>
<EditText
android:id=”@+id/txtUserName”
android:width=”200dp” />
</TableRow>
</TableLayout>

RelativeLayout

The RelativeLayout enables you to specify how child views are positioned relative to
each other. It can be declared like this.
<RelativeLayout
android:id=”@+id/RLayout”
android:layout_width=”fill_parent”
android:layout_height=”fill_parent”
xmlns:android=”http://schemas.android.com/apk/res/android” >
</RelativeLayout>

FrameLayout

The FrameLayout is a placeholder on screen that you can use to display a single view.
It can be declared like this.
<?xml version=”1.0” encoding=”utf-8”?>
<FrameLayout
android:layout_width=”wrap_content”
android:layout_height=”wrap_content”
android:layout_alignLeft=”@+id/lblComments”
android:layout_below=”@+id/lblComments”
android:layout_centerHorizontal=”true” >
<ImageView
android:src = “@drawable/droid”
android:layout_width=”wrap_content”
android:layout_height=”wrap_content” />
</Image view>
</FrameLayout>
Apart form these attributes, there are other attributes that are common in all views and
ViewGroups. They are listed below −

Sr.N View & description


o

1 layout_width
Specifies the width of the View or ViewGroup

2 layout_height
Specifies the height of the View or ViewGroup

3 layout_marginTop
Specifies extra space on the top side of the View or ViewGroup

4 layout_marginBottom
Specifies extra space on the bottom side of the View or
ViewGroup

5 layout_marginLeft
Specifies extra space on the left side of the View or ViewGroup
6 layout_marginRight
Specifies extra space on the right side of the View or ViewGroup

7 layout_gravity
Specifies how child Views are positioned

8 layout_weight
Specifies how much of the extra space in the layout should be
allocated to the View

Units of Measurement

When you are specifying the size of an element on an Android UI, you should
remember the following units of measurement.

Sr.N Unit & description


o

1 Dp
Density-independent pixel. 1 dp is equivalent to one pixel on a
160 dpi screen.

2 Sp
Scale-independent pixel. This is similar to dp and is recommended
for specifying font sizes

3 Pt
Point. A point is defined to be 1/72 of an inch, based on the
physical screen size.
4 Px
Pixel. Corresponds to actual pixels on the screen

Screen Densities

Sr.No Density & DPI

1 Low density (ldpi)


120 dpi

2 Medium density (mdpi)


160 dpi

3 High density (hdpi)


240 dpi

4 Extra High density (xhdpi)


320 dpi

Optimizing layouts

Here are some of the guidelines for creating efficient layouts.

 Avoid unnecessary nesting


 Avoid using too many Views
 Avoid deep nesting

Widgets

Widgets enable users to interact with an Android Studio application page. There
are various kinds of widgets, such as Buttons and TextViews.
To see all the widgets at your disposal, create a new application project called
“Widgets” and select "empty activity". Call your activity “MainActivity”.
There are two components of each Android activity: the XML (Extensible Markup
Language) design (the beauty) and the Java text (the brains).
On the activity_main.xml page, you can see the full widgets palette underneath the
various layout options.

As you can see, there are 20 widgets available for you to use. In this guide, we’ll
discuss TextViews and Buttons, which are probably the most common widgets in
Android development.

Creating a Widget

Your default activity comes with a TextView containing “Hello World”. So you’ve
technically created a widget before this tutorial without even knowing it!
To create another widget, we simply drag and drop the desired widget onto the
desired location on the Android application page.
For example, let’s create a Button at the center of our page. Android Studio will
help us align our widget automatically. Keep in mind that we can also align the
widget by changing its properties, which appear on the XML text page.
Changing Button Text

By default, the Button will have “New Button” as its text element. You can change
the Button’s text by either double-clicking its text or modifying it on the design
page or by scrolling through the Button properties on the right and finding
the text property. Lastly, you can change its text by switching to the XML text tab
and modifying its android:text property.
Let’s make our button say “Change Background Color” by changing the Button
properties on the XML text page to read android:text = “Change Background
Color”
String Resources

You will find that the code is highlighted in yellow after you make the change.
Widget: onClick

If you switch over to the Design page, select the Button widget that we created,
and scroll through its properties, you’ll find the onClick property. onClick allows
you to choose a Java method that the application will call once the Button is
clicked.

Let’s change the onClick properties of our Button to call the method
“changeColor”. Keep in mind that we have to create the changeColor() method in
our Java Class for this onClick command to work.

Widget: changeColor(View view)

Component IDs

To have our changeColor method function, we’ll need to assign IDs to our Layout
and our TextView. By default, our “Hello World” TextView object does not have
an ID and neither does our Layout (which is a RelativeLayout, meaning that it
allows widgets and other components to be aligned relative to each other).
Select the TextView in the top right box, which is titled “Component Tree”. Scroll
through its properties until you see “id”. Change its ID to “text”.
Do the same thing for the RelativeLayout component, but set its ID to “layout”.
You should be able to see the corresponding ID next to each component in the
Component Tree.

Creating the Actual Method

Let’s move onto the actual changeColor method. Go to your MainActivity.java tab.
In this tab, you’ll see a method called onCreate. This runs whenever the app first
starts up.
We’ll create our “changeColor” method right after the onCreate. Add the following
to your MainActivity.java class:
1
2
3
4
5
6
7
8
public void changeColor(View view)
{
RelativeLayout layout = (RelativeLayout)findViewById(R.id.layout);
TextView text = (TextView)findViewById(R.id.text);

layout.setBackgroundColor(Color.RED);
text.setText(R.string.PageIsRed);
}
Our method will turn the color of our layout to red once the button is clicked. It
will also set the TextView object to say “Page is Red”.
For the beginner to Android Studio, there are many things in the code block above
that you should notice.
First, check out our method signature: public void changeColor(View view).
Android requires onClick methods to take a View as a parameter; failure to do so
can cause your app to crash.

Testing the Application

Run the application on an emulator or external debuggable Android device.


Clicking the button changes the color of the layout and alters the TextView as well.
Currently, once the user clicks the button, the widget becomes useless. Try out the
bonus activities to make our button more useful!

Difference Between dp, dip, sp, px, in, mm, pt in Android

This Android tutorial is to explain the difference between dp, dip, sp, px, in, mm,
pt and what we should use when. This is to enable design a consistent UI across
different Android screen sizes. Before going into the difference let us understand
some basic terminologies. Screen size in Android is grouped into categories small,
medium, large, extra large, double-extra and triple-extra. Screen density is the
amount of pixels within an area (like inch) of the screen. Generally it is measured
in dots-per-inch (dpi). Screen density is grouped as low, medium, high and extra
high. Resolution is the total number of pixels in the screen.

 dp: Density Independent Pixel, it varies based on screen density . In 160 dpi
screen, 1 dp = 1 pixel. Except for font size, use dp always.
 dip: dip == dp. In earlier Android versions dip was used and later changed
to dp.
 sp: Scale Independent Pixel, scaled based on user’s font size preference.
Fonts should use sp.
 px: our usual standard pixel which maps to the screen pixel.
 in: inches, with respect to the physical screen size.
 mm: millimeters, with respect to the physical screen size.
 pt: 1/72 of an inch, with respect to the physical screen size.

Always use dp and sp only. sp for font sizes and dp for everything else. It will
make UI compatible for Android devices with different densities.

Formula for Conversion between Units

px = dp * (dpi / 160)

dp to px in device

Following example may help understand better. The scaling occurs based on
bucket size of 120(ldpi), 160(mdpi), 240(hdpi), 320(xhdpi), 480(xxhdpi) and
640(xxxhdpi). The Google suggested ratio for designing is 3:4:6:8:12 for
ldpi:mdpi:hdpi:xhdpi:xxhdpi

A 150px X 150px image will occupy,

 150 dp X 150 dp screen space in mdpi


 100 dp X 100 dp screen space in hdpi
 75 dp X 75 dp screen space in xhdpi

You may use the following DPI calculator to fix your image sizes and other
dimensions when you wish to have an uniform UI design in all Android devices.

Note: When designing an image for Android in Photoshop or other image editing
tools, have the resolution as 72 pixels/inch.

You might also like