0% found this document useful (0 votes)
14 views129 pages

Events (4 Files Merged)

This document discusses widgets and events in Android programming. It begins by defining what a widget is, including examples like TextView, EditText, Button, ImageView and CheckedTextView. It then covers event management using event handlers and listeners. The rest of the document discusses various widget types in more detail, including their XML tags, Java code usage, and common methods.

Uploaded by

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

Events (4 Files Merged)

This document discusses widgets and events in Android programming. It begins by defining what a widget is, including examples like TextView, EditText, Button, ImageView and CheckedTextView. It then covers event management using event handlers and listeners. The rest of the document discusses various widget types in more detail, including their XML tags, Java code usage, and common methods.

Uploaded by

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

Programming with Android:

Widgets and Events

Luca Bedogni Marco Di Felice


Dipartimento di Scienze dell’Informazione
Università di Bologna
Outline

What is a Widget?

Widget: TextView and EditText

Widget: Button and CompoundButton

Widget: ImageView

Widget: CheckedTextView

Event Management: Event Handlers

Event Management: Event Listeners

2
Android: Where are we now …

Android Applications’ anatomy:

Activities  Application Components (screens)


Intents  Communication between components
Layouts  Placement of the elements on the screen …
Views  … Elements to be placed!

Widget  Pre-defined, common-used View objects …

3
Android: Views objects

Views  basic building blocks for user interface components

 Rectangular area of the screen


 Responsible for drawing
 Responsible for event handling

EXAMPLEs of VIEWS objects:

 GoogleMap
 WebView
 Widgets  topic of the day
 …
 User-defined Views

4
Android: Views objects

ViewGroup  Container of other views, base class for layouts

LINEAR LAYOUT TABLE LAYOUT


5
Android: Views objects

Widget Pre-defined interactive UI components (android.view.widgets)

TextView

EditText
Button
ToggleButton
Spinner

DataPicker

6
Widgets: Java and XML code

 Widgets can be created in the XML layout files

< TextView
android:id="@+id/textLabel”
android:width=“100dp”
android:height=“100dp”
android:layout_width="match_parent"
android:layout_height="wrap_content”
android:visibility="visible”
android:enabled="true”
android:scrollbars="vertical”
….
/>
(c) Luca Bedogni 2012
7
Widgets: Java and XML code

 Widgets can be created in Java


 Widgets can be created in XML and accessed in Java

XML
< TextView
android:id="@+id/name1” />

public TextView text; JAVA

text=(TextView)findViewById(R.id.name1);
CAST REQUIRED
public TextView text;
text=new TextView();
(c) Luca Bedogni 2012
8
Widgets: Java and XML code

 Each Widget can generate events, that can be captured by


Listeners that define the appropriate actions to be performed
in response to each event.

ONCLICK event

Java code that


manages the onClick event …

(c) Luca Bedogni 2012


9
Widgets: Java and XML code

 Each Widget can have a focus and a visibility, based on


the user’s interaction.
 The user can force a focus to a specific component through
the requestFocus() method.
 The user can modify the visibility of a specific component
through the setVisibility(int) method.

public TextView text;


text=(TextView) findViewById(R.id.name1);
text.setVisibility(true)
text.requestFocus();
(c) Luca Bedogni 2012
10
Widgets: Hierarchy of the classes …

 Widgets are organized on a hierarchy of classes …

View

TextView ImageView

EditView Button CheckedTextView

AutoCompleteTextView CompoundButton

CheckBox RadioButton ToggleButton

(c) Luca Bedogni 2012


11
Widgets: TextView

 XML tags: <TextView> </TextView>

 Could be filled with strings or HTML markups


 Not directly editable by users
 Usually used to display static informations

<TextView
android:text=”@string/textWelcome"
android:id="@+id/textLabel"
android:layout_width="wrap_content"
android:layout_height="wrap_content”
/>

12
Widgets: TextView methods

 Methods to place some texts inside a TextView …


 public void setText(CharSequence text)
 public CharSequence getText()
public void setSingleLine(boolean singleLine)
public void setHorizontallyScrolling(boolean enable)
public void setLines(int lines)
public void setEllipsize(TextUtils.TruncateAt where)
public void setHints(CharSequence hints)
 TextUtils.TruncateAt.END
 TextUtils.TruncateAt.MARQUEE
 TextUtils.TruncateAt.MIDDLE
 TextUtils.TruncateAt.START
(c) Luca Bedogni 2012
13
Widgets: Linkify elements

 Simple strings could be linkified automatically.


 How? Pick a normal string, and use Linkify.addLinks() to
define the kind of links to be created.
 Could manage: Web addresses, Emails, phone numbers, Maps

TextView textView=(TextView) findViewById(R.id.output);


Linkify.addLinks(textView, Linkify.WEB_URLS |
Linkify.WEB_ADDRESSES |
Linkify.PHONE_NUMBERS );
Linkify.addLinks(textView, Linkify.ALL);

 It is possible to define custom Linkify objects. ..


(c) Luca Bedogni 2012
14
Widgets: EditText

 XML tags: <EditText> </EditText>

 Similar to a TextView, but editable by the users


 An appropriate keyboard will be displayed

<EditText
android:text=”@string/textDefault"
android:id="@+id/editText”
android:inputType= “textCapSentences” | “textCapWords” |
“textAutoCorrect” | “textPassword” |
“textMultiLane” | “textNoSuggestions”
/>

15
Widgets: AutocompleteTextView

 XML tags: <AutoCompleteTextView> </Auto…View>


Used to make easier the input by the users …
As soon as the user starts typing, hints are displayed
A list of hints is given through an Adapter

String[] tips=getResources().getStringArray(R.array.nani_array);
ArrayAdapter<String> adapter=new ArrayAdapter(this,
android.R.layout.simple_dropdown_item_1lines, tips);
AutoCompleteTextView acTextView=(AutoCompleteTextView)
findViewById(R.id.inputText);
acTextView.setAdapter(adapter);

(c) Luca Bedogni 2012


16
Widgets: AutocompleteTextView

(c) Luca Bedogni 2012


17
Widgets: Button

 XML tags: <Button> </Button>

 Superclass of a TextView, but not directly editable by users


Can generate events related to click, long click, drag, etc

<selector>
<Button <item android:color="#ff819191"
android:text="@string/textButton" android:state_pressed="true”>
android:id="@+id/idButton" </item>
android:background="@color/blue” </selector>
/>
res/color/blue.xml

 CompoundButton: Button + state (checked/unchecked)


(c) Luca Bedogni 2012
18
Widgets: Button and CompoundButton

checkBox CompoundButton

XML tags: <CheckBox>


</CheckBox>

<CheckBox
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/buttonCheck"
android:text="CheckBox"
android:checked="true”
/>

(c) Luca Bedogni 2012


19
Widgets: Button and CompoundButton

checkBox CompoundButton

 public boolean isChecked():


Returns true if the button is
checked, false otherwise.

 public boolean
setChecked(bool)

Listener:
onCheckedChangeListener

(c) Luca Bedogni 2012


20
Widgets: Button and CompoundButton

radioButton CompoundButton

XML tags: <RadioButton>


</RadioButton>

<RadioButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/buttonRadio"
android:text="ButtonRadio"
android:checked="true"
/>

(c) Luca Bedogni 2012


21
Widgets: Button and CompoundButton

radioButton CompoundButton

 Define multiple (mutual-


exclusive) options through a
<RadioGroup> tag.

 Only one button can be


checked within the same
RadioGroup.

Listener:
OnCheckedChangeListener

(c) Luca Bedogni 2012


22
Widgets: Button and CompoundButton

<RadioGroup
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical”>
<RadioButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/buttonRadio1"
android:text="Option 1"
android:checked="true” />
<RadioButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/buttonRadio2"
android:text="Option 2” />
</RadioGroup>

(c) Luca Bedogni 2012


23
Widgets: Button and CompoundButton

toggleButton CompoundButton

XML tags: <ToggleButton>


</ToggleButton>

<ToggleButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/toggleButtonId"
android:textOn="Button ON"
android:textOff="Button OFF"
android:checked="false”
/>
(c) Luca Bedogni 2012
24
Widgets: Button and CompoundButton

toggleButton CompoundButton

 It can assume only 2 states:


checked/unchecked

 Different labels for the states


with: android:textOn and
android:textOff XML attributes.

Listener:
OnCheckedChangeListener

(c) Luca Bedogni 2012


25
Widgets: Spinners

Spinner component

XML tags: <Spinner>


</Spinner>
<Spinner
android:layout_width="wrap_content"
android:layout_height="wrap_content"
<resources> android:id="@+id/spinnerId"
<string-array name="stringOptions"> android:entries="@array/stringOptions">
<item>Option 1</item> </Spinner>
<item>Option 2</item>
<item>Option 3</item>
<item>Option 4</item>
</string-array>
</resources> res/values.xml
(c) Luca Bedogni 2012
26
Widgets: Spinners

Spinner component

XML tags: <Spinner>


</Spinner>

 Provides a quick way to select


values from a specific set.
 The spinner value-set can be
defined in XML (through the
entries tag) or through the
SpinnerAdapter in Java
Listener:
OnItemSelectedListener
(c) Luca Bedogni 2012
27
Widgets: Button and CompoundButton

DataPicker component

XML tags: <DataPicker>


</DataPicker>

<DatePicker
android:layout_width="wrap_content"
android:layout_height="wrap_content”
android:id=“@+id/datePickerId”
android:endYear="1990"
android:startYear="2014"
android:maxDate="10/10/2014”
/>

(c) Luca Bedogni 2012


28
Widgets: ImageView

ImageView component

XML tags: <ImageView>


</ImageView>

<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/imageId"
android:src="@drawable/android">

Source: android.jpg in drawable/


(c) Luca Bedogni 2012
29
Widgets: ImageView

 ImageView: subclass of View


object.
 Some methods to manipulate an
image:
 void setScaleType(enum scaleType)
 void setAlpha(double alpha)
 void setColorFilter(ColorFilter color)

CENTER, CENTER_CROP, CENTER_INSIDE,


FIT_CENTER, FIT_END, FIT_START, FIT_XY, MATRIX

(c) Luca Bedogni 2012


30
Widgets: CheckedTextView

Checkable version of a TextView


 Usable with a ListView Adapter
Multiple or single selection of items
(CHOICE_MODE_SINGLE, CHOICE_MODE_MULTIPLE)

 Methods:
 void setChoiceMode(int choiceMode)
 long[] getCheckItemIds()
 int getCheckedItemPosition()

(c) Luca Bedogni 2012


31
Views and Events

Views/Widgets are interactive components …

 … Upon certain action, an appropriate event will be fired

 Events generated by the user’s interaction: click, long


click, focus, items selected, items checked,drag, etc
PROBLEM: How to handle these events?

1. Directly from XML


2. Through Event Listeners (general, recommended)
3. Through Event Handlers (general)
(c) Luca Bedogni 2012
32
Views and Events

 For a limited set of components, it is possible to manage the


events through callbacks, directly indicated in the XML.

<Button
android:text="@string/textButton"
android:id="@+id/idButton" XML Layout File
android:onClick=”doSomething”
/>

public void doSomething(View w) {


Java class // Code to manage the click event
}

(c) Luca Bedogni 2012


33
Views and Events

Views/Widgets are interactive components …

 … Upon certain action, an appropriate event will be fired

 Events generated by the user’s interaction: click, long


click, focus, items selected, items checked,drag, etc
PROBLEM: How to handle these events?

1. Directly from XML


2. Through Event Listeners (general, recommended)
3. Through Event Handlers (general)
(c) Luca Bedogni 2012
34
Views and Events

 Each View contains a collection of nested interfaces


(listeners).

 Each listener handles a single type of events…

 Each listener contains a single callback method …

 The callback is invoked in occurrence of the event.


interface OnClickListener
Button
public abstract void onClick(View v) {}
(c) Luca Bedogni 2012
35
Views and Events: ActionListener

To handle OnClick events through the ActionListener:


1. Implement the nested interface in the current Activity
2. Implement the callback method (onClick)
Button btn = (Button)findViewById(R.id.btn);
3.Associate the ActionListener to the Button through the
View.setOnClickEventListener() method
btn.setOnClickListener(new OnClickListener() {

@Override
public class ExampleActivity extends Activity implements OnClickListener {
… void onClick(View view) {
public
Button button=(Button)findViewById(R.id.buttonNext);
// Event management
button.setOnClickListener(this);

} public void onClick(View v) { } }
});
36
Views and Events: ActionListener

To handle OnClick events through the ActionListener:


1.Create an anonymous OnClickListener object
2.Implement the callback method (onClick) for the anonymous object
Button btn = (Button)findViewById(R.id.btn);
3.Associate the ActionListener to the Button through the
View.setOnClickEventListener() method
btn.setOnClickListener(new OnClickListener() {
Button btn = (Button)findViewById(R.id.btn);
@Override
btn.setOnClickListener(new OnClickListener() {
public void onClick(View view) {
@Override
public void onClick(View view) {
// Event management
// Event management
} }
}); }); (c) Luca Bedogni 2012

37
Views and Events: ActionListener

Some ActionListeners:

 interface OnClickListener
abstract method: onClick()
 interface OnLongClickListener
abstract method: onLongClick()
 interface OnFocusChangeListener
abstract method: onFocusChange()
 interface OnKeyListener
abstract method: onKey()

(c) Luca Bedogni 2012


38
Views and Events: ActionListener

Some ActionListeners:

 interface OnCheckedChangeListener
abstract method: onCheckedChanged()
 interface OnItemSelectedListener
abstract method: onItemSelected()
 interface OnTouchListener
abstract method: onTouch()
 interface OnCreateContextMenuListener
abstract method: onCreateContextMenu()

39
Views and Events: ActionListener

 Possible to fire an event directly from the Java code (without


user’s interaction) … useful for debugging purpose.

 Tipically in the form performXXX()

 The corresponding listener (if set) will be invoked…



Button button=(Button)findViewById(R.id.buttonNext);
button.performClick();
// Callback method

public void onClick(View v) {
….
(c) Luca Bedogni 2012 }
Luca Bedogni, Marco Di Felice – Events and Widgets
40
Views and Events

Views/Widgets are interactive components …

 … Upon certain action, an appropriate event will be fired

 Events generated by the user’s interaction: click, long


click, focus, items selected, items checked,drag, etc

PROBLEM: How to handle these events?


1. Directly from XML
2. Through Event Listeners (general, recommended)
3. Through Event Handlers (general)
Luca Bedogni, Marco Di Felice –(c)Events
Luca Bedogni 2012
and Widgets
41
Views and Events

Event Handlers  Some views have callback methods to


handle specific events
When a Button is touched  onTouchEvent() called

PROBLEM: to intercept an event, you must extend the View class


and override the callback method … not very practical!

 In practice: Events Handlers are used for custom (user-


defined) components …
 … Events Listeners are used for common View/Widget
components …
(c) Luca Bedogni 2012
42
Activity
An activity is a single, focused thing that the
user can do. Almost all activities interact with
the user, so the Activity class takes care of
creating a window for you in which you can
place your UI with setContentView(View).

Each Activity has its own:


XML Tag in AndroidManifest.xml
Java implementation
XML Layout file
Activity XML Tag in AndroidManifest.xml
Activity Java file
Activity resources-xml file
Activity resources -design
Intent Definition
Intent: facility for late run-time binding between
components of the same or different applications.
 Call a component from another component
 Possible to pass data between components
 Components: Activities, Services, Broadcast receivers

 Something like:
 “Android, please do that with these data”
 Reuse already installed applications and components
Intents
We can think to an Intent object as a
message containing a bundle of
information.
Component Name

Action Name

Data
Structure
of an Intent Category

Extra Flags

 Intent is sent from current Activity to a receiver


Activity which is then activated and executed.
INTENT TYPES

Explicit : The target receiver is specified through


the Component Name
Used to launch specific Activities

Implicit :the target receiver is specified through the


actions to be executed.
The system chooses the receiver that matches the
request.
Explicit Intents

In Explicit Intent  Specify the name of the Activity


that will handle the intent.

• Used to control the execution flow between Activities


belonging to the same Android application
Example 1

• To starts the second activity fro the first activity


In the first activity :

1. Build a new Intent message

Intent intent=new Intent(this,SecondActivity.class);

2- Specify the Activity who will receive the Intent

3- Fire the Intent through the startActivity()

startActivity(intent);
Explicit Intent:
• To send parameter from activity to another one use :
intent.putExtra(“KEY”, VALUE);
Ex:
intent.putExtra(“grade”,75);
intent.putExtra(“name”,”Ali”);
intent.putExtra(“grade”,true);
 To retrieve the parameters inserted from the calling
Activity
intent.getExtras().getTYPE(“KEY”);
Ex:
intent.getExtras().getInt(“grade”);
intent.getExtras().getString(“name”);
intent.getExtras().getBoolean(“grade”);
Explicit Intents

• Some Activities can return results to the caller Activity


Intent intent = new Intent(this, SecondActivity.class);
startActivityForResult(intent, CHOOSE_ACTIVITY_CODE);
• First Activity the wait for second activity to finish

Activity 1 Activity 2
Explicit Intents

• In the second Activity


Intent intent=new Intent();
setResult(RESULT_OK, intent);
intent.putExtra(”result", resultValue);
finish();

Activity 1 Activity 2
Explicit Intents

• In the First Activity


• The method
public void onActivityResult(int requestCode, int
resultCode, Intent data) {
// Invoked when SecondActivity completes its
operations
IMPLICIT INTENT
The target receiver is specified
through the actions to be executed.
• Actions : Call, Contact,Browser,Gallery,Camera
..etc.
The system chooses the receiver

that matches the request.


• Implicit Intents  do not name a target
(component name is left blank) but an
intention of what to do …
IMPLICIT INTENT
 When an Intent is launched, Android checks out which
Activies might answer to the Intent …
 If at least one is found, then that Activity is started
 Binding does not occur at compile time, nor at install time,
but at run-time …(late run-time binding)
Implicit Intent: Action Examples
Action Name Description
• Action Name

ACTION_IMAGE_CAPTURE Open the camera and receive a photo
ACTION_VIDEO_CAPTURE Open the camera and receive a video
ACTION_DIAL Open the phone app and dial a phone
number
ACTION_SENDTO Send an email (email data contained in the
extra)
ACTION_SETTINGS Open the system setting
ACTION_WIRELESS_SETTINGS Open the system setting of the wireless
interfaces
ACTION_EDIT Display data to edit
ACTION_MAIN Start as a main entry point, does not
expect to receive data.
ACTION_PICK Pick an item from the data, returning what
was selected.
ACTION_VIEW Display the data to the user
ACTION_SEARCH Perform a search
IMPLICIT INTENT

1. Build a new Intent message


2. Specify only the Action you want to perform
3. Fire the Intent through the
startActivity()
Intent intent=new
Intent(MediaStore.ACTION_IMAGE_CAPTURE);

startActivity(intent);
Implicit Intent: Examples

1. Build a new Intent message


2. Specify only the Action you want to perform
3. Fire the Intent through the startActivity()
4. Verify whether the Intent can be handled

Intent intent=new
Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if
(intent.resolveActivity(getPackageManager
()) != null) {
startActivity(intent);
}
Implicit Intent: Action Examples
 Data passed from the caller to the called Component.

 Def. of the data (URI) and Type of the data (MIME type)
Uniform Resource Identifier (URI)

1. void setData(Uri)
2. void setType(String)
Implicit Intent: Examples
Intent intent=new
Intent(Intent.ACTION_DIAL);
intent.setData(Uri.parse("tel:0123456789"));
startActivity(intent);

Intent intent=new
Intent(Intent.ACTION_VIEW);
intent.setData(
Uri.parse("content://contacts/people/1"));
startActivity(intent);
Implicit Intent: Examples

Intent intent=new
Intent(Intent.ACTION_VIEW);

intent.setData(
Uri.parse(”http://www.cs.unibo.it"));

startActivity(intent);
Implicit Intent: Type

In an Intent, the Data is specified by a name and a type

TYPE: Multipurpose Internet Mail Extensions (MIME)

type/subtype

image/gif image/jpeg image/png


text/html text/plain text/css
video/mpeg4 … … … …
Implicit Intent: setType Example
Use method setType(MIME) to define the data input of
an Implicit Intent

Intent sendIntent = new Intent();


sendIntent.setAction(Intent.ACTION_SEND);
sendIntent.putExtra(Intent.EXTRA_TEXT,
textMessage);
sendIntent.setType(HTTP.PLAIN_TEXT_TYPE);
startActivity(sendIntent)
Implicit Intent: Category
 Category
 A string containing information about the kind of component
that should handle the Intent.

 More than one can be specified for an Intent

 void addCategory(String)

Category Name Description


CATEGORY_HOME The activity displays the HOME screen.
CATEGORY_LAUNCHER The activity is listed in the top-level
application launcher, and can be displayed.
CATEGORY_PREFERENCE The activity is a preference panel.
CATEGORY_BROWSABLE The activity can be invoked by the browser to
display data referenced by a link.
27
Implicit Intent

1. Build a new Intent message

2. Specify only the Category of the receiver Activity

3. Fire the Intent through the startActivity()

Intent intent=new Intent();


Intent.setAction(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_HOME);

startActivity(intent);
Implicit Intent Intent Resolution

QUESTION: How can Android know which application


to call after an Implicit Intent is fired?

ANSWER: Each application declares the Intent is able


to handle in the AndroidManifest.xml file
If an Intent with Action name ACTION_ECHO is invoked, the Activity is
lanched

<intent-filter>
<action android:name=”ACTION_ECHO” />
</intent-filter>
The Intent resolution process resolves the
Intent-Filter that can handle a given Intent
(e.g. ACTION_ECHO).

Three tests must be passed:


1. Action field test
2. Category field test
3. Data field test

If the Intent-filter of Activity A passes all the three


test, then
it is selected to handle the Intent.
Intent Resolution
(ACTIONTest): The action specified in the Intent
must match one of the actions listed in the filter.

 If the filter does not specify any action  FAIL


 An Intent that does not specify an action 
SUCCESS
as as long as the filter contains at least one
action.
<intent-filer … >
<action
android:name=“com.example.it.ECHO”/>
</intent-filter>
31
Intent Resolution
(CATEGORY Test): Every category in the Intent must
match a category of the Intent Filter.

 If the category is not specified in the Intent 


Android assumes it is CATEGORY_DEFAULT,
thus the filter must include this category to
handle the Intent.
<intent-filer … >
<category
android:name=“android.intent.category.DEFAULT
”/>
</intent-filter>
32
Intent Resolution
(DATA Test): The URI of the intent is compared
with the parts of the URI mentioned in the filter
(this part might be incompleted).

<intent-filer … >
<data android:mimeType=“audio/*
android:scheme=“http”/>
<data android:mimeType=“video/mpeg
android:scheme=“http”/>
</intent-filter>

 Both URI and MIME-types are compared (4 different sub-


cases …)
Programming with Android:
Application Resources
Outline

What is a resource?

Declaration of a resource

Resource type: integer, string, array

Resource type: color, dimension, style

Resource type: drawable, raw, xml

Defining Configuration-specific resources

Providing the Best resources for a device

2
Application Resources Definition

 An Application is composed of: code and resources.

DEF. Resources are everything that is not code (including:


XML layout files, language packs, images, audio/video files, etc)

Utilization of Resources… why?

 Separate data presentation (layout) from data management


 Provide alternative resources to support specific device
configurations (e.g. different language packs)
 Re-compile only when strictly needed!

3
Application Resources Definition

PROBLEM. An Android application might run on heterogenous devices


with different characteristics (e.g. screen size, language support,
keyboard type, input devices, etc).

11,868 different devices in 2013!

4
Application Resources Definition

The same application layout with 8 buttons, on a tablet


and on a smartphone (Nexus 7) device.

Find the differences …

5
Application Resources Definition

PROBLEM. An Android application might run on heterogenous devices


with different characteristics (e.g. screen size, language support,
keyboard type, input devices, etc).

TRADITIONAL SOLUTION. Foresee all the alternatives in Java code


 The code is full of if-else cases
 Recompile when need to change layout or add a new language package.

ANDROID SOLUTION. Separate code from application resources

 Use declative XML-based approch to define resources (images,


files, layout, text, etc)
6
Application Resources Definition

 Use XML files to define


Java App Code (declarative approach):
- Application Layout
- Text used in the
applications
- Application Menu
XML Layout File
Device 1,2 - Animations
- …
XML String File
Italian, English, French
- Foresee different
resources alternatives
XML Animation File for different device
configurations (e.g. screen
resolution, language, input
…….. Resources devices. etc)
7
Application Resources Definition

EXAMPLE
- Build the application layout
through XML files (like HTML)
- Define two different XML layouts
for two different devices
Device 1 Device 2 - At runtime, Android detects the
HIGH screen pixel density LOW screen pixel density
current device configuration and
Java App Code loads the appropriate resources
for the application
- No need to recompile!
- Just add a new XML file if you
need to support a new device
XML Layout File XML Layout File
Device 1 Device 2
8
Application Resources Definition

The same application layout with 8 buttons, on a tablet


and on a smartphone (Nexus 7) device.

LAYOUT LAYOUT
SMARTPHONE TABLET

9
Application Resources Definition

 Resources are defined in the res/ folder of the project.

MyProject

src MyActivity.java (Source Code Java)

res

layout main.xml (Application XML Layout)

values strings.xml (Application Labels)

drawable icon.png (Application Icons)

10
Application Resources Definition

Resource Type Resource contained


res/animator XML files that define property animations.
res/anim XML files that define tween animations.
res/color XML files that define a state list of colors.
res/drawable Bitmap files (.png, .9.png, .jpg, .gif) or XML
files that are compiled into other resources.

res/layout XML files that define a user interface layout.


res/menu XML files that define application menus.
res/raw Arbitrary files to save in their raw form.
res/values XML files that contain simple values, such as
strings, integers, array.

res/xml Arbitrary XML files.

11
Application Resources Definition

 Resources are defined in a declarative way through XML.


 Each resource has a name/identifier (see details later).
Example: string.xml contains all the text that the application uses. For
example, the name of buttons, labels. default text, etc

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


<resources> Resource type
(string)
<string name="hello”> Hello world! </string>
<string name="labelButton"> Insert your username </string>

</resources>

12
Application Resources Definition

 Resource can be accessed in the Java code through the R


class, that works as a glue between the world of java and the
world of resources.
 Automatically generated file, no need to modify it.
 Recreated in case of changes in the res/ directory.

public final class R {


R contains
public static final class string { resource IDs
public static final int hello=0x7f040001; for all the
public static final int label1=0x7f040005; resources in the
res/ directory.
}
}

13
Application Resources Definition

 Resources can be accessed from Java code by using the R


class and methods of the Activity class (details later).
 We just need to know the resource Identifier (ID) … how to
know it? (see next slides)


final String hello=getResources().getString(R.string.hello);
final String label=getResources().getString(R.string.labelButton);
Log.i(STRING_TAG,” String1 “ + hello);
Log.i(STRING_TAG,” String2 “ + label);

14
Application Resources Definition

STEP0: Declare resources in res/ STEP2: Access resources through R class

public final class R {


<?xml version="1.0" encoding="utf-8"?>
<resources>
public static final class string {
public static final int hello=0x7f040001;
<string name="hello”> Hello </string>
public static final int label1=0x7f040005;
<string name="label1"> Label </string>
}
</resources>
}
XML-Based, Declarative Approach
Java Code, Programmatic Approach

STEP1: Compile the project

15
Access to Application Resources

 Each Resource is associated with an Identifier (ID), that


is composed of two parts:
 The resource type: Each resource is grouped into a "type,” (e.g.
string, color, menu, drawable, layout, etc)
 The resource name, which is either: the filename, excluding the
extension; or the value in the XML <android:name> attribute.
 Identifiers must be unique!!

 Two ways to access resources:


 From the Java Code
 From the XML files
16
Access to Application Resources: XML

@[<package_name>:]<resource_type>/<resource_name>

 <package_name> is the name of the package in which


the resource is located (not required when referencing
resources from the same package)
 <resource_type> is the the name of the resource type
 <resource_name> is either the resource filename without
the extension or the android:name attribute value in the
XML element.

17
Access to Application Resources: XML

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


<resources>
<color name="opaque_red">#f00</color>
<string name=”labelButton”> Submit </string>
<string name=”labelText”> Hello world! </string>
</resources>

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


<resources>
<Textview android:id=“@+id/label1” android:text=“@string/labelText”
android:textcolor=“@color/opaque_red”>
</Textview>
<Button android:id=“@+id/button1” android:text=“@string/labelButton”>
</Button>
</resources>

18
Access to Application Resources: Java

[<package_name>.]R.<resource_type>.<resource_name>

 <package_name> is the name of the package in which


the resource is located (not required when referencing
resources from the same package)
 <resource_type> is the R subclass for the resource type
 <resource_name> is either the resource filename without
the extension or the android:name attribute value in the
XML element.

19
Access to Application Resources: Java

// Get a string resource from the string.xml file


final String hello=getResources().getString(R.string.hello);

// Get a color resource from the string.xml file


final int color=getResources().getColor(R.color.opaque_red);

// Load a custom layout for the current screen


setContentView(R.layout.main_screen);

// Set the text on a TextView object using a resource ID


TextView msgTextView = (TextView) findViewById(R.id.label1);
msgTextView.setText(R.string.labelText);

20
Resources Types: string and array

Resource File Java constant XML tag Description


Type
string Any file in the R.string.<key> <string> String value
res/values/ associated to a key.

integer Any file in the R.integer.<key> <integer> Integer value


res/values/ associated to a key.

array Any file in the R.array.<key> <string-array> Array of strings.


res/values/ <item> Each element is a
<item> described by an
</string-array> <item>
array Any file in the R.array.<key> <integer-array> Array of integers.
res/values/ <item> Each element is a
<item> described by an
</integer-array> <item>
21
Resources Types: string and array

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


<resources> MYVALUES.XML

<string name=“app_title”> Example Application </string>


<string name=“label” > Hello world! </string>
<integer name=“val” > 53 </integer>
<string-array name=“nameArray”>
<item> John </item>
<item> Michael </item>
</string-array>
<integer-array name=“valArray”>
<item> 1 </item>
<item> 2 </item>
</integer-array>

</resources>
22
Resources Types: string and array

MYFILE.JAVA

// Access the string value


final String hello=getResources().getString(R.string.app_title);

// Access the string-array values


final string[] nameS=getResources().getStringArray
(R.array.nameArray);

// Access the integer-array values


final int[] val=getResources().getIntArray(R.array.valArray);

23
Resources Types: string and array

 Resources can be defined in the res/string.xml or in any


other file defined by the users (File  New  Android XML File)

24
Resources Types: string and array

 Android XML Files can be edited by hand or through the


Eclipse plugin (recommended).

25
Other Resources Types

 Some other resources types (we will meet later …)

Resource File Java constant XML tag Description


Type
layout Any file in the R.layout.<key> <layout> Defines a layout
res/layout/ of the screen

animation Any file in the R.animator. <animator> Defines a


res/animator/ <key> property
animation (not the
only method!)
menu Any file in the R.menu.<key> <menu> User-defined
res/menu/ menus with
multiple options

26
Resources Types: color, dimension, style

Resource File Java constant XML tag Description


Type
color Any file in the R.color.<key> <color> Definition of
res/values/ colors used in the
GUI
dimension Any file in the R.dimen.<key> <dimen> Dimension units
res/values/ of the GUI
components

style/theme Any file in the R.style.<key> <style> Themes and


res/values/ styles used by
applications or by
components

27
Resources Types: color, dimension, style

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


<resources> STYLES.XML

<color name=“red”> #FF0000 </color>


<color name=“red_trasparent” > #66DDCCDD</color>

</resources>

 Color values can be defined based on one of these syntax


rules: #RGB, #ARGB, #RRGGBB, #AARRGGBB (R=red,
G=green, B=blue, A=transparency).
 From Java code:
int redTransparent=getResources.getColor(R.color.red_transparent)

28
Resources Types: color, dimension, style

Code Description
px Pixel units
in Inch units
mm Millimeter units
pt Points of 1/72 inch
dp Abstract unit, independent from pixel density of a display

sp Abstract unit, independent from pixel density of a display (font)

These units are relative to a 160 dpi (dots per inch) screen, on which 1dp is roughly
equal to 1px. When running on a higher density screen, the number of pixels used
to draw 1dp is scaled up by a factor appropriate for the screen's dpi. Likewise,
when on a lower density screen, the number of pixels used for 1dp is scaled down

29
Resources Types: color, dimension, style

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


<resources>

<dimen name="textview_height">25dp</dimen>
<dimen name="textview_width">150dp</dimen>
<dimen name="font_size">16sp</dimen>
</resources>

 Applying dimensions to attributes in the XML layout:

<TextView
MAIN.XML
android:layout_height="@dimen/textview_height"
android:layout_width="@dimen/textview_width"
android:textSize="@dimen/font_size"/>

30
Resources Types: color, dimension, style

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


<resources>

<dimen name="textview_height">25dp</dimen>
<dimen name="textview_width">150dp</dimen>
<dimen name="font_size">16sp</dimen>
</resources>

 Applying dimensions to attributes in the XML layout:

<TextView
MAIN.XML
android:layout_height="@dimen/textview_height"
android:layout_width="@dimen/textview_width"
android:textSize="@dimen/font_size"/>

31
Resources Types: color, dimension, style

 A Style is a set of attributes that can be applied to a specific


component of the GUI (View) or to the whole screen or
application (in this case, it is also referred as “theme”).

 A style is an XML resource that is referenced using the value


provided in the name attribute.

 Styles can be organized in a hierarchical structure. A style


can inherit properties from another style, through the parent
attribute.

 Use <style></style> tags to define a style in the res/ folder.


Use <item> to define the attributes of the style.

32
Resources Types: color, dimension, style

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


<resources>
<style name="CustomText" parent="@style/Text">
<item name="android:textSize">20sp</item>
<item name="android:textColor">#008</item>
</style>
</resources>

 Applying a style to a View in the XML layout:

<EditText style="@style/CustomText"
MAIN.XML
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Hello, World!" />

33
Resources Types: drawable

Resource File Java constant XML tag Description


Type
drawable Any file in the R.drawable. <drawable> Images and
res/drawable/ <key> everything that
can be drawn
A Drawable resource is a general concept for a graphic that can be
drawn on the screen:
 Images
 XML resources with attributes such as android:drawable and
android:icon (e.g. a Button can have a drawable resource as
background)
Complete list of drawable resource type can be found here:
http://developer.android.com/guide/topics/resources/drawable-resource.html
34
Resources Types: drawable

 A BitMap file is a .png, .jpg or a .gif file.


 Android creates a BitMap resource for any of these files
saved in the res/drawable directory.
This layout XML applies the file myimage.png saved in res/drawable to a View.
<ImageView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:src=”drawable/myimage" />

Retrieve the image as a Drawable from Java:


Drawable draw=res.getDrawable(R.drawable.myimage);

35
Resources Types: drawable

 An XMLBitmap is an XML resource that points to a bitmap file.

 Usage: (i) Alias to the raw bitmap file, (ii) Specifiy additional
properties such as dithering and tiling.

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


<bitmap xmlns:andoid=http://schemas.android.com/apk/res/android”
andoid:src=“@drawable/tile”
andoid:tileMode=“repeat”>

Some properties of an XMLBitmap:


android:src, android:antialias, android:dither, android:filter, android:gravity

36
Resources Types: drawable

Drawable type Description


BitMap File A bitMap Graphic file (.png, .gif. .jpeg)
Nine-Patch File A PNG file with stretchable regions to allow resizing
Layer List A Drawable managing an array of other drawable
State List A Drawable that references different graphis based on the states
Level List An XML managing alternate Drawables. Each assigned a value
Transition A Drawable that can cross-fade between two Drawable
Inset A Drawable that insets another Drawable by a specific distance
Clip A Drawable that clips another Drawable based on its current level
Scale A Drawable that changes the size of another Drawable
Shape An XML file that defines a geometric shape, colors and gradients

Complete list of drawable resource type can be found here:


http://developer.android.com/guide/topics/resources/drawable-resource.html

37
Resources Types: xml and raw

Resource File Java constant XML tag Description


Type
xml Any file in the R.xml.<key> <xml> User-specific XML
res/xml/ file with name
equal to key
raw Any file in the R.raw.<key> <raw> Raw resources,
res/raw/ accessible through
the R class but not
optimized
Used to define resources for which no run-time optimization must be performed
(e.g. audio/video files). They can be accessed an a stream of bytes, by using Java
InputStream objects:

InputStream is= getResources().openRawResource(R.raw.videoFile)

38
Resources Types: xml and raw

 The res/xml folder might contain arbitrary XML files that can be read
at runtime through the R.xml.<filename> constant.

 It is possible to parse the XML file through a XMLResourceParser


object, that implements an XML parser:

XMLResourceParser parser=getResources().getXML(R.xml.myfile)

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


<names>
<name code=”1234”>Marco Di Felice </item>
<name code=4324">Luca Bedogni </item>
</names>

39
Resources Alternatives

 Android applications might provide alternative resources to


support specific device configurations (e.g. different languages).

 At runtime, Android detects the current device configuration and


loads the appropriate resources for the application.

 To specify configuration-specific alternatives:

1. Create a new directory in res/ named in the form


<resources_name>-<config_qualifier>

2. Save the respective alternative resources in this new directory

40
Resources Alternatives

Name of the folder: <resources_name>-<config_qualifier>.


 <resources_name> is the directory name of the corresponding
default resources (see previous slides).
 <qualifier> is a name that specifies an individual configuration for
which these resources are to be used (see next slide).

res

values-it Values for the IT locale

values-en Values for the EN locale

41
Resources Alternatives: Qualifiers

Configuration Values Example Description


MCC and MNC mcc310, mcc208, etc mobile country code (MCC)
Language and region en, fr, en-rUS, etc ISO 639-1 language code
smallestWidth sw320dp, etc shortest dimension of screen
Available width w720dp, w320dp, etc minimum available screen width
Available height h720dp, etc minimum available screen height
Screen size small, normal, large screen size expressed in dp
Screen aspect long, notlong aspect ratio of the screen
Screen orientation port, land screen orientation (can change!)
Screen pixel density (dpi) ldpi, mdpi, hdpi screen pixel density
Keyboard availability keysexposed, etc type of keyword
Primary text input method nokeys, qwerty availability of qwerty keyboard
Navigation key availability navexposed, etc navigation keys of the application
Platform Version (API v3, v4, v7, etc API supported by the device
level)
42
Resources Alternatives

 Android applications might provide alternative resources to


support specific device configurations (e.g. different languages).

 At runtime, Android detects the current device configuration and


loads the appropriate resources for the application.

 To specify configuration-specific alternatives:

1. Create a new directory in res/ named in the form


<resources_name>-<config_qualifier>

2. Save the respective alternative resources in this new directory

43
Resources Alternatives Matching

 When the application


requests a resource for
which there are multiple
alternatives, Android
selects which alternative
resource to use at
runtime, depending on the
current device
configuration, through the
algorithm shown in the
Figure.

44
Resources Alternatives Matching

DEVICE CONFIGURATION

Locale = it Screen orientation = port


Screen pixel density = hdpi
Touchscreen type = notouch
Primary text input method = 12key

drawable/
drawable-it/
drawable-fr-rCA/
drawable-it-port/
drawable-it-notouch-12key/
drawable-port-ldpi/
drawable-port-notouch-12key/

45
Resources Alternatives Matching

DEVICE CONFIGURATION

Locale = it Screen orientation = port


Screen pixel density = hdpi
Touchscreen type = notouch
Primary text input method = 12key

drawable/
drawable-it/
drawable-fr-rCA/
drawable-it-port/
drawable-it-notouch-12key/
drawable-port-ldpi/
drawable-port-notouch-12key/

46
Resources Alternatives Matching

DEVICE CONFIGURATION

Locale = it Screen orientation = port


Screen pixel density = hdpi
Touchscreen type = notouch
Primary text input method = 12key

drawable/
drawable-it/
drawable-fr-rCA/
drawable-it-port/
drawable-it-notouch-12key/
drawable-port-ldpi/
drawable-port-notouch-12key/

47
Resources Alternatives

BEST PRACTICE

 Provide default resources for your application.


 Provide alternative resources based on the
target market of your application.
 Avoid unnecessary or unused resources
alternatives.
 Use alias to reduce the duplicated resources.
48
Kingdom of Saudi Arabia
Ministry of Education
Prince Sattam Bin Abdulaziz University ‫وزارة اﻟﺗﻌﻠﯾم‬
College of Computer ‫ﺟﺎﻣﻌﺔ اﻻﻣﯾر ﺳطﺎم ﺑن ﻋﺑد اﻟﻌزﯾز‬
Engineering and sciences ‫ﻛﻠﯾﺔ ھﻧدﺳﺔ وﻋﻠوم اﻟﺣﺎﺳب‬
Department of Computer Sciences
‫ﻗﺳم ﻋﻠوم اﻟﺣﺎﺳب‬
Course Title and Code: Mobile Applications
:‫اﺳﻢ اﻟﻄﺎﻟﺒﺔ‬
development CS4831
Second Exam
Instructor Name: Dr. Ahmed Ghneimat
Semester I :‫اﻟﺮﻗﻢ اﻟﺠﺎﻣﻌﻲ‬
Dr Aisha Abuduulahi
1439/1440
Date: 05-03-1440 H
:‫رﻗﻢ اﻟﺸﻌﺒﺔ‬
Time: 60 minutes

Instructions ‫ﺗﻌﻠﯿﻤﺎت‬
▪ This exam consists of (2) questions on 3 pages. ‫ ﺻﻔﺤﺎت‬3 ‫( أﺳﺌﻠﺔ ﻋﻠﻰ‬2) ‫ھﺬا اﻻﺧﺘﺒﺎر ﻣﺆﻟﻒ ﻣﻦ‬ ▪
▪ All questions should be answered on the same sheets
▪ Electronic devices that could have a memory is not
‫ﺟﺎوب ﻋﻠﻰ ﺟﻤﯿﻊ اﻷﺳﺌﻠﺔ ﻋﻠﻰ ﻧﻔﺲ اﻻوراق‬ ▪
allowed for theoretical part ‫ﯾﻤﻨﻊ اﺳﺘﻌﻤﺎل اﻻﺟﮭﺰة اﻻﻟﻜﺘﺮوﻧﯿﺔ اﻟﺘﻲ ﺗﺤﺘﻮي ﻋﻠﻰ ذاﻛﺮة‬ ▪
▪ Traditional calculator is allowed ‫ﻟﻠﺠﺰء اﻟﻨﻈﺮي‬
▪ Examination rules must be adhered. (‫ﯾﺴﻤﺢ ﺑﺎﺳﺘﻌﻤﺎل اﻻﻟﺔ اﻟﺤﺎﺳﺒﺔ )دون ذاﻛﺮة‬ ▪
● Books or other related materials are NOT allowed
.‫ﯾﺠﺐ اﻻﻟﺘﺰام ﺑﺠﻤﯿﻊ ﻗﻮاﻧﯿﻦ وﻟﻮاﺋﺢ اﻻﻣﺘﺤﺎﻧﺎت‬ ▪
● Use blue pen only
‫ﻻ ﯾﺴﻤﺢ ﺑﺎﻟﻜﺘﺐ أو اﻟﻤﻮاد ذات اﻟﺼﻠﺔ داﺧﻞ ﻏﺮﻓﺔ اﻻﻣﺘﺤﺎن‬ ▪
‫اﻟﻜﺘﺎﺑﺔ ﺗﻜﻮن ﺑﺎﻟﻘﻠﻢ اﻷزرق ﻓﻘﻂ‬ ▪

Mobile Applications Development Second Exam - 1439-1440(First Semester)Page: 1 of 6


Q1 ) – (5 Marks)
a- Choose the most appropriate answer

1. For an activity that has the following intent-filter,


<intent-filter>
<action android:name=”android.intent.action.SEND”/>
<action android:name=”android.intent.action.VIEW”/>
<category android:name=”android.intent.category.DEFAULT”/>
<data android:mimeType=”text/*”/>
</intent-filter>

Which of the following intents should pass this filter?


1) Intent intent = new Intent(Intent.ACTION_DIAL);
2) Intent intent = new Intent(Intent.ACTION_SEND); intent.setType("text/plain"); and
3) Intent intent = new Intent();

2. The utilities of using android resources are


a) Separate between data presentation and data management
b) Provide alternative resources to support different device specifications
c) Force a recompile whenever a new device is supported
d) a & b

3. To access a string resource called ‘day’, in a package that’s called android in java
a) R.android.string.day
b) String.android.R.day
c) [email protected]
d) android.R.string.day

4. A single intent definition may contain


a) Component Name with a flag, and data.
b) Data, category, and extra.
c) Action and data and the component name
d) An action, data and extras

5. RESULT_OK, means that ..


a) The click event is successfully executed
b) The intent has successfully returned the requested results
c) The drawable has been successfully displayed
d) a & b

b- Match the terms from the numbered column with statements in the second
1. R class 5 Used as an Alias to raw image files, and to specify additional properties
too
2. Explicit intents 3 Has a set of attributes to apply on a specific UI component
3. Style 6 Launch an activity expecting results upon its closure
4. onActivityResult 1 Automatically generated file, recreated if res/ directory is modified
5. XMLBitmap 2 Controls the application flow between activities in the same application
6. startActivityForResult 4 Used to handle the results sent from second activity

Mobile Applications Development Second Exam - 1439-1440(First Semester)Page: 2 of 6


Q2 Develop an application to the following specifications:
Design and write an android application that enables a simplified chatting between two activities. The first
activity sends messages to the second, and the second responds to these messages.

a) The activities design must be like the ones in the figure 1 (4 marks)
Set the application name to Chat Application
Define all the labels in the app as resources.
b) In the first activity (left), if the user clicks the ‘send’ button, the text in the edit text must be sent
to the second activity. (3 marks)

c) In the second activity: (3 marks)


o If the user clicks ‘answer’, the text in the edit text must be sent back to the first activity.
o If the user clicks ‘share’, an intent with ACTION_SEND must be issued, which enables the
user to share the received text through a list of other applications installed on the device

Note Copy the XML and Java file for each activity and upload it to the blackboard
Eaxm2

Mobile Applications Development Second Exam - 1439-1440(First Semester)Page: 3 of 6


string.xml

<resources>
<string name="app_name">ChatApplication</string>
<string name="send">Send</string>
<string name="textInit">Nothing is sent yet</string>
<string name="editHint">Enter your message here .. </string>
<string name="answer">Answer</string>
<string name="share">Share</string>
</resources>

activity_main.xml

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


<LinearLayout 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"
android:orientation="vertical"
tools:context="com.example.satalites55.chatapplication.MainActivity">

<TextView
android:id="@+id/received"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/textInit"
/>
<EditText
android:id="@+id/sender"
android:hint="@string/editHint"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<Button
android:id="@+id/send"
android:text="@string/send"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:onClick="send"/>

</LinearLayout>

MainActivity.java

package com.example.satalites55.chatapplication;

import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {


EditText editText;
TextView textView;
public static final int REQUEST_CODE = 1;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
editText = findViewById(R.id.sender);
textView = findViewById(R.id.received);

Mobile Applications Development Second Exam - 1439-1440(First Semester)Page: 4 of 6


}

public void send(View v){


Intent intent = new Intent(this, Main2Activity.class);
String sent = editText.getText().toString();
intent.putExtra("sender", sent);
startActivityForResult(intent, REQUEST_CODE);
}

public void onActivityResult(int requestCode, int resultCode, Intent data){


String received= data.getExtras().getString("receiver");
textView.setText(received);
editText.setText("");
}
}

activity_main2.xml

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


<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.satalites55.chatapplication.Main2Activity">

<TextView
android:id="@+id/sent"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>

<EditText
android:id="@+id/receiver"
android:hint="@string/editHint"
android:layout_width="match_parent"
android:layout_height="wrap_content" />

<Button
android:id="@+id/answer"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:onClick="answer"
android:text="@string/answer" />

<Button
android:id="@+id/button"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:onClick="share"
android:text="@string/share" />

</LinearLayout>

Main2Activity.xml
package com.example.satalites55.chatapplication;

import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

public class Main2Activity extends AppCompatActivity {


EditText editText;

Mobile Applications Development Second Exam - 1439-1440(First Semester)Page: 5 of 6


TextView textView;
String sender;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
editText = findViewById(R.id.receiver);
textView = findViewById(R.id.sent);
Intent intent = getIntent();
sender = intent.getExtras().getString("sender");
textView.setText(sender);
}

public void answer(View v) {


Intent intent = new Intent();
setResult(RESULT_OK, intent);
String answer = editText.getText().toString();
intent.putExtra("receiver", answer);
finish();

public void share(View v) {


Intent shareIntent = new Intent(Intent.ACTION_SEND);
shareIntent.putExtra(Intent.EXTRA_TEXT, sender);
shareIntent.setType("text/plain");
if (shareIntent.resolveActivity(getPackageManager()) != null)
startActivity(shareIntent);
}
}

Mobile Applications Development Second Exam - 1439-1440(First Semester)Page: 6 of 6

You might also like