Thanks to visit codestin.com
Credit goes to www.scribd.com

0% found this document useful (0 votes)
5 views78 pages

Unit II

The document provides an overview of user interaction in Android applications, focusing on input components and UI controls. It explains how to create UI elements using XML and programmatically, detailing various controls such as TextView, EditText, Button, and others. Additionally, it covers the implementation of alert dialogs and option menus in Android development.

Uploaded by

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

Unit II

The document provides an overview of user interaction in Android applications, focusing on input components and UI controls. It explains how to create UI elements using XML and programmatically, detailing various controls such as TextView, EditText, Button, and others. Additionally, it covers the implementation of alert dialogs and option menus in Android development.

Uploaded by

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

Introduction

UNIT- II USER INTERACTION

1
Introduction
USER INTERACTION:

Input Components:

Generally, in android the user interface of an app is made with a collection of View and ViewGroup objects.

 The ViewGroup is a subclass of View and it will act as a base class for layouts and layout parameters.

 The ViewGroup will provide invisible containers to hold other Views or ViewGroups and to define the layout

properties.

In android, we can define a UI or input controls in two ways, those are

 Declare UI elements in XML

 Create UI elements at runtime

2
Introduction
Declare UI Elements in XML:
 In android, we can create layouts same as web pages in HTML by using default Views and ViewGroups in the XML
file. The layout file must contain only one root element, which must be a View or ViewGroup object.
 Following is the example of defining UI controls (TextView, EditText, Button) in the XML file (activity_main.xml) using
LinearLayout.
Example:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="@+id/fstTxt"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Enter Name" />
3
Introduction
<EditText
android:id="@+id/name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:ems="10"/>
<Button
android:id="@+id/getName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Get Name" />
</LinearLayout>

4
Create UI Element at Runtime:
public class MainActivity extends AppCompatActivity

@Override

protected void onCreate(Bundle savedInstanceState)

super.onCreate(savedInstanceState);

TextView textView1 = new TextView(this);

textView1.setText("Name:");

EditText editText1 = new EditText(this);

editText1.setText("Enter Name");

Button button1 = new Button(this);

button1.setText("Add Name");

LinearLayout linearLayout = new LinearLayout(this);

linearLayout.addView(textView1); 5
Introduction
Input Components

 Android UI Controls are those components of Android that are used to design the UI in a more interactive way.
 It helps us to develop an application that makes user interaction better with the view components.
 TextView
 EditText
 Button
 ImageButton
 ToggleButton
 RadioButton
 CheckBox
 ProgressBar
 Spinner
 TimePicker
 DatePicker 6

 SeekBar
Introduction

7
Introduction
TextView
Text View is a UI Component that displays the text to the user on their Display Screen.
We can create it in two ways:
XML file:
For this, we declare it in the layout tag as follows:
<Linear Layout xmls:android= "http://schemas.android.com/apk/res/android"
<TextView
//attributes to describe it/>
</LinearLayout>
Activity file:
In this, we declare it using the setText() method as follows:
LinearLayout linearlayout_name = (LinearLayout)findViewById(R.id.LinearLayout);
TextView textview_name = new TextView(this);
textveiw_name.setText(“Hello I am Text View”);
linearLayout.addView(textView);
setContentView(R.layout.activity_main);
8
Introduction
EditText
EditText is a user interface control that allows the users to enter some text.
We can create it in two ways:
XML file:
For this, we declare it in the layout tag as follows:
<Linear Layout xmls:android= ”http://schemas.android.com/apk/res/android”>
<EditText
//attributes
>
</LinearLayout>
Activity file:
In activity, we declare it using the getText() method as follows:
LinearLayout linearlayout_name = (LinearLayout) findViewById (R.id.LinearLayout) ;
EditText edittext_name = new EditText(this);
edittext_name.setHint(“Hello I am EditText”);
linearLayout.addView(edittext_name);
setContentView(R.layout.activity_main);

9
Introduction
Button:
This is a UI that is used to perform some action as soon as the user clicks on it.
We can create it in two ways:
XML file:
For this, we declare it in the layout tag as follows:
<Linear Layout xmls:android= ”http://schemas.android.com/apk/res/android”>
<Button
//attributes
/>
</LinearLayout>
Activity file:
In activity, we declare it programmatically as below:
LinearLayout linearlayout_name = (LinearLayout)findViewById(R.id.LinearLayout);
Button btn_name = new Button(this);
btn_name.setText(“Hello I am Button”);
linearLayout.addView(btn_name);
setContentView(R.layout.activity_main);
10
Introduction
ImageButton
 It is the same as a Button but it’s used to display an image on the button to perform an Action. In this, we
need to give the source of the image so that the system can load it.
 We can create it in two ways:
 It is the same as a Button but it’s used to display an image on the button to perform an Action. In this, we
need to give the source of the image so that the system can load it.
We can create it in two ways:
XML file:
For this, we declare it in the layout tag as follows:
<Linear Layout xmls:android= ”http://schemas.android.com/apk/res/android”>
<ImageButton
//other attributes...
android:src= “@drawable/add_icon”/>
</LinearLayout>
Activity file:
In the activity file, we declare it programmatically as below:
LinearLayout linearlayout_name = (LinearLayout)findViewById(R.id.LinearLayout);
ImageButton btn_name = new Button(this);
btn_name.setImageResource(R.drawable.add_icon);
linearLayout.addView(btn_name);
setContentView(R.layout.activity_main);
11
Introduction
ToggleButton
The toggle button displays the ON/OFF states of a button with a light indicator.
We can create it in two ways:
XML file:
For this, we declare it in the layout tag as follows:
<Linear Layout xmls:android= ”http://schemas.android.com/apk/res/android”>
<ToggleButton
//attributes
android:checked="true"
android:textOff="OFF"
android:textOn="ON"/>
</LinearLayout>
Activity file:
In the activity file we declare it programmatically as below:
LinearLayout linearlayout_name = (LinearLayout)findViewById(R.id.LinearLayout);
ToggleButton tb_name = new ToggleButton(this);
tb_name.setTextOff("OFF");
tb_name.setTextOn("ON");
tb_name.setChecked(true);
linearLayout.addView(btn_name);
setContentView(R.layout.activity_main);
12
Introduction
RadioButton
 Radio button in Android is the one that has only two possible states, that are either checked or
unchecked.
 Initially, it is in the unchecked state, once it’s checked it can’t be unchecked.
We can create it in two ways:
XML file:
For this, we declare it in the layout tag as follows:
<Linear Layout xmls:android= ”http://schemas.android.com/apk/res/android”>
<RadioButton
android:text="Radio button"
android:checked="true"/>
</LinearLayout>
Activity file:
In the activity file, we declare it programmatically as below:
LinearLayout linearlayout_name = (LinearLayout)findViewById(R.id.LinearLayout);
RadioButton btn_name = new RadioButton(this);
btn_name.setText("Hello");
btn_name.setChecked(true);
linearLayout.addView(btn_name);
setContentView(R.layout.activity_main);

13
Introduction
RadioGroup
It’s a group of Radio buttons that are alike. In this, only one of all the buttons can be chosen.
We can create it in two ways:
XML file:
For this, we declare it in the layout tag as follows:
<Linear Layout xmls:android= ”http://schemas.android.com/apk/res/android”>
<RadioGroup android:orientation="vertical">
<RadioButton android:text="Radio Button 1"/>
<RadioButton android:text="Radio Button 2"/>
<RadioButton android:text="Radio Button 3"/>
</RadioGroup>
</LinearLayout>
In the activity file,
RadioButton rdb1,rdb2,rdb3;
@override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
rdb1 = (RadioButton)findViewById(R.id.rdb_1);
rdb2 = (RadioButton)findViewById(R.id.rdb_2);
rdb3 = (RadioButton)findViewById(R.id.rdb_3);
Button btn = (Button)findViewById(R.id.getBtn);
setContentView(R.layout.activity_main);
}
14
Introduction
CheckBox
 A CheckBox is the UI control that has two states that are either checked or unchecked.
 If we have a group of CheckBox, we can select as many as we want, unlike RadioGroup.
We can create it in two ways:
XML file:
For this, we declare it in the layout tag as follows:
<Linear Layout xmls:android= ”http://schemas.android.com/apk/res/android”>
<CheckBox
android:checked="true"
android:text="CheckBox"
// other attributes
/>
</LinearLayout>
Activity file:
In activity, we declare it programmatically as below:
LinearLayout linearlayout_name = (LinearLayout)findViewById(R.id.LinearLayout);
CheckBox cb_name = new CheckBox(this);
cb_name.setText("DataFlair");
cb_name.setChecked(true);
layout.addView(cb_name);
setContentView(R.layout.activity_main);

15
Introduction
ProgressBar
In Android, we have a progress bar that shows the progress of some action that is happening like pasting a file to some
location. A progress bar can be in two modes:
Determinate Mode:
In this, the progress is shown with the percent of action completed. Also, the time to be taken is already determined.
Indeterminate Mode:
In this, there is no idea of when the task would be completed, therefore, it functions continuously.
We can create it in two ways:
XML file:
For this, we declare it in the layout tag as follows:
<Linear Layout xmls:android=”http://schemas.android.com/apk/res/android”>
<ProgressBar
// attributes, here we define the speed, layout, id, etc.
/>
</LinearLayout>
Activity file:
In activity, we declare it programmatically as below:
LinearLayout linearlayout_name = (LinearLayout)findViewById(R.id.LinearLayout);
pgsBar pgs_name=new pgsBar(this);
layout.addpgsBar(pgs_name);
setContentView(R.layout.activity_main);
Here we need to set the sleep time and override the onClick() and onCreate() methods
The above were some of the very important UI controls, now we will also read about some more UI controls :
16
Introduction
ImageView In Android

 In Android, ImageView class is used to display an image file in application. Image file is easy to use but hard to

master in Android, because of the various screen sizes in Android devices. An android is enriched with some of the

best UI design widgets that allows us to build good looking and attractive UI based application.

 Important Note: ImageView comes with different configuration options to support different scale types. Scale type

options are used for scaling the bounds of an image to the bounds of the imageview. Some of them scaleTypes

configuration properties are center, center_crop, fit_xy, fitStart etc. You can read our ScaleType tutorial to learn all

details on it.

Below is an ImageView code in XML:

Make sure to save lion image in drawable folder

17
Introduction
Below is an ImageView code in XML:

<ImageView

android:id="@+id/simpleImageView"

android:layout_width="fill_parent"

android:layout_height="wrap_content"

android:src="@drawable/lion" />

18
Introduction
Alert Dialogues

 Alert Dialogs are the UI elements that pop up when the user performs some crucial actions with the application.
 These are the window like elements that may contain multiple or single items to select from the list or it may have the
error message and some action buttons.
Example:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity"
tools:ignore="HardcodedText">

<Button
android:id="@+id/openAlertDialogButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:layout_marginTop="64dp"
android:text="OPEN ALERT DIALOG"
android:textSize="18sp" />

19
Introduction
<TextView
android:id="@+id/selectedItemPreview"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:layout_marginTop="16dp"
android:text="Selected Item is : "
android:textSize="18sp" />
</LinearLayout>

20
Introduction
MainActivity.java
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import android.annotation.SuppressLint;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {

// Button and TextView instances


Button bOpenAlertDialog;
TextView tvSelectedItemPreview;

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

bOpenAlertDialog = findViewById(R.id.openAlertDialogButton);
tvSelectedItemPreview = findViewById(R.id.selectedItemPreview);
21
Introduction
final int[] checkedItem = {-1};

bOpenAlertDialog.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {

AlertDialog.Builder alertDialog = new AlertDialog.Builder(MainActivity.this);

alertDialog.setIcon(R.drawable.image_logo);

alertDialog.setTitle("Choose an Item");

final String[] listItems = new String[]{"Android Development", "Web Development", "Machine Learning"};

alertDialog.setSingleChoiceItems(listItems, checkedItem[0], new DialogInterface.OnClickListener() {


@SuppressLint("SetTextI18n")
@Override
public void onClick(DialogInterface dialog, int which) {

checkedItem[0] = which;

// now also update the TextView which previews the selected item
tvSelectedItemPreview.setText("Selected Item is : " + listItems[which]);

// when selected an item the dialog should be closed with the dismiss method
dialog.dismiss();
}
});

22
Introduction
alertDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {

}
});

// create and build the AlertDialog instance


// with the AlertDialog builder instance
AlertDialog customAlertDialog = alertDialog.create();

// show the alert dialog when the button is clicked


customAlertDialog.show();
}
});
}
}

23
Introduction
Android Option Menu :

 Android Option Menus are the primary menus of android. They can be used for settings, search, delete

item etc.

 Here, we are going to see two examples of option menus. First, the simple option menus and second,

options menus with images.

 Here, we are inflating the menu by calling the inflate() method of MenuInflater class. To perform event

handling on menu items, you need to override onOptionsItemSelected() method of Activity class.

24
Introduction
menu_main.xml

<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
tools:context="example.javatpoint.com.optionmenu.MainActivity">

<item android:id="@+id/item1"
android:title="Item 1"/>
<item android:id="@+id/item2"
android:title="Item 2"/>
<item android:id="@+id/item3"
android:title="Item 3"
app:showAsAction="withText"/>
</menu>

25
Introduction
MainActivity.java
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}

26
Introduction
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
switch (id){
case R.id.item1:
Toast.makeText(getApplicationContext(),"Item 1 Selected",Toast.LENGTH_LONG).show();
return true;
case R.id.item2:
Toast.makeText(getApplicationContext(),"Item 2 Selected",Toast.LENGTH_LONG).show();
return true;
case R.id.item3:
Toast.makeText(getApplicationContext(),"Item 3 Selected",Toast.LENGTH_LONG).show();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
}

27
Introduction

28
Introduction
Android Popup

 Android Popup Menu displays the menu below the anchor text if space is available otherwise above the

anchor text. It disappears if you click outside the popup menu.

 The android.widget.PopupMenu is the direct subclass of java.lang.Object class.

 android.widget.PopupWindow. This class represents a popup window that can be used to display an

arbitrary view. The popup window is a floating container that appears on top of the current activity

29
Introduction
MainActivity.java
package example.javatpoint.com.popupmenu;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.PopupMenu;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {


Button button;

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

button = (Button) findViewById(R.id.button);


button.setOnClickListener(new View.OnClickListener() {

30
Introduction
@Override
public void onClick(View v) {
//Creating the instance of PopupMenu
PopupMenu popup = new PopupMenu(MainActivity.this, button);
//Inflating the Popup using xml file
popup.getMenuInflater().inflate(R.menu.popup_menu, popup.getMenu());

//registering popup with OnMenuItemClickListener


popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
public boolean onMenuItemClick(MenuItem item) {
Toast.makeText(MainActivity.this,"You Clicked : " + item.getTitle(), Toast.LENGTH_SHORT).show();

return true;
}
});

popup.show();//showing popup menu


}
});//closing the setOnClickListener method
}
}
31
Introduction

32
Introduction
Screen Navigation through App Bar:

 The app bar, also known as the action bar, is one of the most important design elements in your app's

activities, because it provides a visual structure and interactive elements that are familiar to users.

 In the early stages of developing an app, you should determine the paths users should take through your

app in order to do something, such as placing an order or browsing through content.

 Each path enables users to navigate across, into, and back out from the different tasks and pieces of

content within the app.

33
Introduction
Types of Navigation link:

 The Up button is always used to navigate to the parent screen in the hierarchy. It differs from
the Back button which provides navigation to whatever screen the user viewed previously.
 Tabs are most appropriate for four or fewer sibling screens. The user can tap a tab to see a different
screen, or swipe left or right to see a different screen.

34
Introduction
Forward Navigation Link:
Forward navigation refers to one of three types of movement between screens to complete a task:
Downward in an app's hierarchy to access deeper content, from a parent screen (higher level of hierarchy)
to a child screen (lower level)
Reverse Navigation Link:
Reverse navigation refers to backward movement between screens. It can move
users chronologically through their recent screen history, or upwards through an app's hierarchy.
Reverse chronological navigation
Reverse chronological navigation refers to navigating in reverse order through a user's history of recently
viewed screens. It can move users between screens within an app or across multiple apps. For example,
the Back button on a web browser is a form of reverse chronological navigation.
This type of navigation is typically provided by the operating system or platform. Individual platforms
define how it behaves and how users can access that functionality.

35
Introduction
Screen Navigation through App Bar:

36
Introduction
Providing Up Navigation
 The up navigation will allow our application to move to previous activity from the next activity. It can be
done like this.
 To implement Up navigation, the first step is to declare which activity is the appropriate parent for each
activity. You can do it by specifying parentActivityName attribute in an activity. Its syntax is given below

android:parentActivityName = "com.example.test.MainActivity"
After that you need to call setDisplayHomeAsUpEnabled method of getActionBar() in the onCreate method
of the activity. This will enable the back button in the top action bar.

getActionBar().setDisplayHomeAsUpEnabled(true);
The last thing you need to do is to override onOptionsItemSelected methodThe ID for the action is
android.R.id.home.Its syntax is given below −
public boolean onOptionsItemSelected(MenuItem item) {

switch (item.getItemId()) {
case android.R.id.home:
NavUtils.navigateUpFromSameTask(this);
return true;
} }

37
Introduction
Handling device back button
 Since you have enabled your back button to navigate within your application, you might want to put the
application close function in the device back button.
 It can be done by overriding onBackPressed and then calling moveTaskToBack and finish method. Its
syntax is given below −
@Override
public void onBackPressed() {
moveTaskToBack(true);
MainActivity2.this.finish();
}
Apart from this setDisplayHomeAsUpEnabled method, there are other methods available in ActionBar API
class.

38
Introduction
RecyclerView:
The RecyclerView class extends the ViewGroup class and implements ScrollingView interface. It is introduced in Marshmallow.
It is an advanced version of the ListView with improved performance and other benefits. RecyclerView is mostly used to design
the user interface with the fine-grain control over the lists and grids of android application.
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.RecyclerView
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:scrollbars="vertical"
android:id="@+id/recyclerView"
tools:context="example.javatpoint.com.recyclerviewlist.MainActivity">
</android.support.v7.widget.RecyclerView>

39
Introduction
list_item.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/relativeLayout"
android:layout_width="match_parent"
android:layout_height="?android:attr/listPreferredItemHeightLarge"
android:background="@drawable/border">
<TextView
android:id="@+id/textView"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_toEndOf="@id/imageView"
android:layout_toRightOf="@id/imageView"
android:gravity="center_vertical"
android:textSize="16sp"/>
</RelativeLayout>
40
Introduction

border.xml

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


<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<solid android:color="#FFFFFF" />
<stroke
android:width="1dp"
android:color="#CCCCCC" />
</shape>

41
Introduction
MainActivity.java

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;

public class MainActivity extends AppCompatActivity {

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

MyListData[] myListData = new MyListData[] {


new MyListData("Email", android.R.drawable.ic_dialog_email),
new MyListData("Info", android.R.drawable.ic_dialog_info),
new MyListData("Delete", android.R.drawable.ic_delete),
new MyListData("Dialer", android.R.drawable.ic_dialog_dialer),

42
Introduction

new MyListData("Alert", android.R.drawable.ic_dialog_alert),


new MyListData("Map", android.R.drawable.ic_dialog_map),
new MyListData("Email", android.R.drawable.ic_dialog_email),
new MyListData("Info", android.R.drawable.ic_dialog_info),
new MyListData("Delete", android.R.drawable.ic_delete),
new MyListData("Dialer", android.R.drawable.ic_dialog_dialer),
new MyListData("Alert", android.R.drawable.ic_dialog_alert),
new MyListData("Map", android.R.drawable.ic_dialog_map),
};
RecyclerView recyclerView = (RecyclerView) findViewById(R.id.recyclerView);
MyListAdapter adapter = new MyListAdapter(myListData);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
recyclerView.setAdapter(adapter);
} }

43
Introduction
Output:

44
Material Design:

 Beautifully design one layout window. By uniting style, branding, interaction, and motion.

STM-boris beizer 45
 Material Design which was introduced in Android Lollipop version.

 In Material Design lot of new things were introduced like Material Theme, new widgets, customshadows, vector

drawables and custom animations

STM-boris beizer 46
STM-boris beizer 47
Introduction
Testing the User Interface: Expresso:

 Espresso is a testing framework for Android to make it easy to write reliable user interface tests.

 Espresso automatically synchronizes your test actions with the user interface of your application.

 The framework also ensures that your activity is started before the tests run.

 Google released the Espresso framework in October 2013 and, as of release version 1.0

48
Introduction
Testing the User Interface: Expresso:

49
Introduction

Features of Espresso:

 Some the salient features supported by Espresso are as follow,

 Very simple API and so, easy to learn.

 Highly scalable and flexible.

 Provides separate module to test Android WebView component.

 Provides separate module to validate as well as mock Android Intents.

 Provides automatic synchronization between your application and tests.

50
Introduction
Prerequisites

 Espresso is a user interface-testing framework for testing android application developed in Java / Kotlin

language using Android SDK. Therefore, espresso’s only requirement is to develop the application

using Android SDK in either Java or Kotlin and it is advised to have the latest Android Studio.

 Install latest Java JDK and configure JAVA_HOME environment variable.

 Install latest Android Studio (version 3.2. or higher).

 Install latest Android SDK using SDK Manager and configure ANDROID_HOME environment variable.

 Install latest Gradle Build Tool and configure GRADLE_HOME environment variable.

51
Introduction

 You'll also need to make sure you have the Android Support Repository version 15+ installed.

 It's recommended to turn off system animations on the device or emulator we will be using. Since
Espresso is a UI testing framework, system animations can introduce flakiness in our tests.
Under Settings => Developer options disable the following 3 settings and restart the device: 52
Introduction

53
Introduction

Finally, we need to pull in the Espresso dependencies and set the test runner in
our app build.gradle:

// build.gradle
...
android {
...
defaultConfig {
...
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}
}

54
Introduction

Creating a Simple Espresso Test:


 The code below shows a simple Espresso test that enters some text into an EditText and then verifies the text entered. It's

based off the standard new project template which has a single MainActivity that contains a TextView with the text "Hello

world!".

 1. Add an EditText to MainActivity that has id = R.id.etInput.

 2. Create a new class MainActivityInstrumentationTest inside of the default instrumentation tests directory

(src/androidTest/java). The best practice is to mimic the same package structure with your tests as your product code. This

has the benefit of giving your tests access to package-private fields in your product code. For this example, we'll be creating

MainActivityInstrumentationTest at src/androidTest/java/com.codepath.espressodemo.MainActivityInstrumentationTest.

55
Introduction

MainActivityInstrumentationTest.java
import static android.support.test.espresso.Espresso.onView;

import static android.support.test.espresso.action.ViewActions.typeText;

import static android.support.test.espresso.assertion.ViewAssertions.matches;

import static android.support.test.espresso.matcher.ViewMatchers.withId;

// Tests for MainActivity

public class MainActivityInstrumentationTest {

// Preferred JUnit 4 mechanism of specifying the activity to be launched before each test

@Rule

public ActivityTestRule<MainActivity> activityTestRule =

new ActivityTestRule<>(MainActivity.class);
56
Introduction

@Test

public void validateEditText()

onView(withId(R.id.etInput)).perform(typeText("Hello")).check(matches(withText("Hello")));

57
Introduction

Creating a Simple Espresso Test:


 The code below shows a simple Espresso test that enters some text into an EditText and then verifies the text entered. It's

based off the standard new project template which has a single MainActivity that contains a TextView with the text "Hello

world!".

 1. Add an EditText to MainActivity that has id = R.id.etInput.

 2. Create a new class MainActivityInstrumentationTest inside of the default instrumentation tests directory

(src/androidTest/java). The best practice is to mimic the same package structure with your tests as your product code. This

has the benefit of giving your tests access to package-private fields in your product code. For this example, we'll be creating

MainActivityInstrumentationTest at src/androidTest/java/com.codepath.espressodemo.MainActivityInstrumentationTest.

58
Introduction

Running Espresso Tests

 There are 2 ways to run your tests:

 1. Run a single test through Android Studio:

 o Right click on the test class and select Run:

 2. Run all the tests through Gradle:

 o Open the Gradle window and find connectedDebugAndroidTest under Tasks =>

verification.

 o Right click and select Run

59
Introduction

Running Espresso Tests

60
Intents:

An intent is to perform an action on the screen.

Android intents are mainly used to:

 Start the service

 Launch an activity

STM-boris beizer 61


Example:

Activity_main.xml;p

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

<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"

xmlns:app="http://schemas.android.com/apk/res-auto"

xmlns:tools="http://schemas.android.com/tools"

android:layout_width="match_parent"

android:layout_height="match_parent"

tools:context="example.MainActivity">

<EditText

android:id="@+id/editText"

android:layout_width="wrap_content"

android:layout_height="wrap_content"
STM-boris beizer 62
android:layout_marginEnd="8dp"
<Button

android:id="@+id/button"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:layout_marginRight="8dp"

android:layout_marginLeft="156dp"

android:layout_marginTop="172dp"

android:text="Visit"

app:layout_constraintTop_toBottomOf="@+id/editText" />

STM-boris beizer 63
MainActivity.java:

import android.content.Intent;

import android.net.Uri;

import android.support.v7.app.AppCompatActivity;

import android.os.Bundle;

import android.view.View;

import android.widget.Button;

import android.widget.EditText;

public class MainActivity extends AppCompatActivity {

Button button;

EditText editText;

STM-boris beizer 64
@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);

button = findViewById(R.id.button);

editText = findViewById(R.id.editText);

button.setOnClickListener(new View.OnClickListener() {

@Override

public void onClick(View view) {

String url=editText.getText().toString();

Intent intent=new Intent(Intent.ACTION_VIEW, Uri.parse(url));

startActivity(intent);

} STM-boris beizer 65
Output:

STM-boris beizer 66
Output:

STM-boris beizer 67
Introduction

Adapter:

In Android, Adapter is a bridge between UI component and data source that helps us to fill data in UI component.

It holds the data and send the data to an Adapter view then view can takes the data from the adapter view and

shows the data on different views like as ListView, GridView, Spinner etc

68
Introduction
ADAPTER VIEWS

69
ListView:

70
GridView

STM-boris beizer 71
Spinner:

STM-boris beizer 72
STM-boris beizer 73
Activity_main.xml :

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"

xmlns:tools="http://schemas.android.com/tools"

android:layout_width="match_parent"

android:layout_height="match_parent"

android:orientation="vertical"

tools:context=".MainActivity">

<ListView android:id="@+id/Dog_List"

STM-boris beizer 74
android:layout_width="match_parent"
MainActivity.java;
import android.os.Bundle;

import android.widget.ArrayAdapter;

import android.widget.ListView;

import androidx.appcompat.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity

@Override

protected void onCreate(Bundle savedInstanceState)

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);
STM-boris beizer 75
Dog_List:

"Husky", "Labrador", "Chow Chow", " Beagle ", " Rottweiler ", " Doberman ", "Chihuahua",

" Pit Bull ", "Pug", "Golden Retriever ", "German Shepherd", "Great Dane", "Boxer"

STM-boris beizer 76
Output:

STM-boris beizer 77

You might also like