0% found this document useful (0 votes)
0 views101 pages

Android 1 Introduction

The document provides an overview of Android mobile development, covering essential topics such as project structure, components, user interfaces, and activity lifecycle. It includes tutorials, examples, and exercises aimed at teaching the creation of Android applications from scratch. Key elements discussed include activities, intents, services, and user interface components like buttons and dialogs.

Uploaded by

vicentselfa
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)
0 views101 pages

Android 1 Introduction

The document provides an overview of Android mobile development, covering essential topics such as project structure, components, user interfaces, and activity lifecycle. It includes tutorials, examples, and exercises aimed at teaching the creation of Android applications from scratch. Key elements discussed include activities, intents, services, and user interface components like buttons and dialogs.

Uploaded by

vicentselfa
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/ 101

IES Jaume II el Just

Tavernes de la Valldigna

Mobile
development

Vicent Selfa
Curs 2020/2021
Android :
Introduction

Android developer
Android
Index
● Interesting links
● Starting with Android
– Elements of an Android project
– Components and activities
– My first Android project
– Logs, dialogs and toasts
– A multi-language application
● User interfaces
– Layouts
– Buttons and Toggle Buttons
– CheckBoxes and RadioButtons
– Webviews
– ListView and adapters
– 1.- The first way: A built-in adapter
– 2.- Using a handmade layout
– 3.- Using SimpleAdapter
Android

● Interesting links
Tutorials:
• Android tutorial
This tutorial will teach you basic Android programming and will also
take you through some advance concepts related to Android application
development.
• Curso de programación Android
Con el Curso de Programación en Android de sgoliver.net aprenderás a
crear desde cero tus propias aplicaciones para dispositivos móviles
con sistema operativo Android.

Video: Android and Android Studio: Getting Started


Learn how to get started with Android and Android Studio in this short tutorial.
It demonstrates how to install Android Studio (Google’s official Android IDE)
and create your first Android app.

Android APP development:


A complete guide about Android APP development
Android
● Starting with Android
Projects act as containers for storing things such as code and
resource files. The SDK tools expect your projects to follow a
specific structure so it can compile and package your application
correctly.

There are three types of projects, and they all share the same
general structure but differ in function:

Android Projects: An Android project is the container for your


application's source code, resource files, and files. An application
project is the main type of project and the contents are eventually
built into an .apk file that you install on a device.
Test Projects: These projects contain code to test your application
projects and are built into applications that run on a device.
Library Projects: These projects contain shareable Android source
code and resources that you can reference in Android projects. This
is useful when you have common code that you want to reuse.
Android
● Elements of an Android project
The following directories and files comprise an Android project:
src/ Contains your java files, organized in components.
bin/ Here you can find the final .apk file and other compiled resources.
gen/ Contains the Java files generated by ADT, such as your R.java file and
interfaces created from AIDL files.
assets/ This is empty. You can use it to store raw asset files.
res/ Contains application resources, such as drawable files, layout files, and
string values. The definitions for all resources of a particular application package
will be put into the R class.
drawable/ For bitmap files (PNG, JPEG, or GIF), 9-Patch image files, and XML
files that describe Drawable shapes or Drawable objects that contain multiple
states (normal, pressed, or focused).
layout/ XML files that are compiled into screen layouts (or part of a screen).
menu/ For XML files that define application menus. See the resource type.
values/ For XML files that are compiled into many kinds of resource.
xml/ For miscellaneous XML files that configure application components.
libs/ Contains private libraries
Android
● Elements of an Android project
AndroidManifest.xml
The control file that describes the nature of the application and each of its
components.
project.properties
This file contains project settings, such as the build target.
local.properties
Customizable computer-specific properties for the build system.
ant.properties
Customizable properties for the build system.
build.xml
The Ant build file for your project.
This is only applicable for projects that you build with Ant

Project general description


Android
● Components of an Android project

Views (Layouts):
They make the user interface and are defined in an XML file
like what would be the definition of a web page in HTML.
Activities (Java programs):
An activity may represent an application screen, I mean, a
java program and a layout file. So often we use various
activities to create a user interface.
Intents
May represent an attempt to perform some action,
such as a phone call or view a website. In many cases, they
will be initialized not by the application, but by the system

// The intent
Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
// Adding information to the intent
cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, uriFichero);
// Starting activity
startActivityForResult(cameraIntent, 1);
Android
● Components of an Android project
Services
Process that runs in the background without needing interaction with the user. It's like a
demon Linux or a Windows service. Android has two types of services:
Local services: applications that can be used for the same terminal.
Remote service: they can be used from other terminals.
Android services
Android Services - Tutorial

Content Providers:
Standard mechanism for applications to share data without compromising the security of
the file system. With this device you can access data from other applications, such as
contact list or provide data to other applications.

Android content providers


Android
● Activities: Steps
1.- Creating an activity:
Create a class extending the Activity class and implement the callback
functions, at least the onCreate method.
public class MainActivity extends Activity { // ….
public void onCreate(Bundle savedInstanceState) { // …
2.- Establishing the user interface
Add the command setContentView (resource) into the event onCreate
(layout). setContentView(R.layout.activity_main);
3.- Declaring the activity into the AndroidManifest file
<activity android:name="com.example.threads1.MainActivity"
android:label="@string/app_name" > </activity>
4.- Launching activities
1.- Select the icon of the activity
2.- From another activity making an intent with Intent (className) and with
the methods:
startActivity() or startActivityForResult ()
5.- Finishing an activity
Using the function: finish()
Android
● Activities:
Lifecycle
Android
● My first Android project: Hello World!

Exercise.- Create a new


project: My Application
Android
●The first project: Basic things
1.- Creating an activity:
public class MainActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout. activity_main);
}
} 2.- Establishing the user interface

3.- Declaring the activity into the AndroidManifest file

<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category 4.- The launcher
android:name="android.intent.category.LAUNCHER" /> activity
</intent-filter>
</activity>
Android
●The first project
<?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=".MainActivity">

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/hello"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />

</android.support.constraint.ConstraintLayout>

<resources>
<string name="app_name">My Application</ string>
<string name="hello">Hello 2n DAM students!
</string>
</resources>
Android
●The first project: Modifying the view
Views

Toolbar

Palette Design
editor
Attributes

Design view Blueprint view


Component
Tree

Android Studio layout editor


Blueprint view
Android
●The first project: Modifying the view
Exercise: Modify the activity_main.xml, string.xml and colors.xml files
to get the next view.

<resources>
<color name="colorPrimary">#008577</ color>
<color name="colorPrimaryDark">#00574B</ color>
<color name="colorAccent">#00E6694A</ color>
<color name="colorBlue">#12188A</ color>
<color name="colorRed">#BB0A3C</ color>
<color name="colorYellow">#F0D656</ color>
</resources>
<resources>
<string name="app_name">My Application</ string>
<string name="helloEN">Hello 2n DAM students!</ string>
<string name="helloVA">Hola alumnes de 2n
DAM!</string>
<string name="helloES">Hola alumnos de 2o
DAM!</string>
</resources>

Then take a look to the xml code generated.


Android
●The first project: Modifying the view

By default we are using constraint


layout. So, first clear all constraints

Then organize texts

And, for finishing, infer new


constraints
Android
The first project:
Adding methods to the MainActivity class

onCreate (): called when the activity is first created.


onStart () is called when the activity is visible to the user.
onResume () is called when the activity begins to interact with the user.
onPause (): called when the current activity is interrupted and the
previous activity is resumed.
onStop () is called when the activity is no longer visible to the user.
onDestroy (): called before the activity is destroyed by the system
(manually or by the system to save memory).
onRestart (): is called when the activity has been stopped and restarted.

Activity lifecycle
Activity reference
Android
The first project:
Adding methods to the MainActivity class

Debugging your application


Android
The first project:
Adding methods to the MainActivity class

String tag = "Events"; // To filter special messages MainActivity.java


@Override
public void onStart() {
super.onStart();
Log.d(tag, "onStart() event"); Log.d(tag, "onStart() event");
}
import android.util.Log;

To show the logcat window … if disappears!

The Log class reference.


Android
The first project:
Adding methods to the MainActivity class
Android Monitor
Add other methods: onResume, onPause … to your MainActivity class
to get the next Log messages.

Log.d
Android
The first project:
Adding methods to the MainActivity class

A toast provides simple feedback about an operation in a small


popup. It only fills the amount of space required for the message and
the current activity remains visible and interactive.

Add the next method to your MainActivity


MainActivity.java
public void displayToast (String text) {
int duration = Toast.LENGTH_LONG;
Toast toast = Toast.makeText(this, text, duration);
toast.show();
}

The Toast class reference.


Android
The first project:
Adding methods to the MainActivity class
MainActivity.java
// Calling the displayToast method from onStart()
Add the next code to your MainActivity
String tag = "Events";
@Override
public void onStart() {
super.onStart();
displayToast("onStart() event");
}

Using the displayToast function, add some toasts to your


onCreate() and onResume() methods to show messages like these.
Android
The first project:
Adding methods to the MainActivity class

public void buildDialog (String title, String message) {


AlertDialog.Builder builder = new AlertDialog.Builder(this); // this = the context
builder.setTitle(title); builder.setMessage(message);
builder.setPositiveButton("OK", null);
builder.create(); builder.show();
} MainActivity.java

Exercise: Add a call to the buildDialog function


to your previous method onStart() to get something
like this at the start of the activity.
Then make similar calls to the function from the
methods: onPause(), onResume() …

@Override
public void onStart() {
super.onStart();
displayToast( "onStart() event");
buildDialog ("onStart() action", "Starting ...");
}
Android
The first project:
Adding methods to the MainActivity class

Exercise: Add new buttons to your buildDialog function to


show something like this.

AlertDialog
AlertBuilder Reference
AlertDialog exemple
Android
The first project:
Adding methods to the MainActivity class

•Add a new picture to your drawable folder.


•Then show that icon into your buildDialog using the setIcon() method.
•To finish, add a new more button into the buildDialog.

R.drawable.android_moving
Android
The first project:
Adding methods to the MainActivity class
A bit more complicated code:
• What is going to happen after changing the line
builder.setPositiveButton("OK", null);
for the next code?

builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {


@Override
public void onClick (DialogInterface dialog, int which) {
displayToast ("Has fes click en OK. El valor de which és: “ + which);
}
});
MainActivity.java

Exercise: What are the values of which in the other two buttons?
Android
The first project:
Adding methods to the MainActivity class

Exercise: Adding a button to finish your application

Modifying the view: 1.- Adding a button

2.- Adding an onClick() attribute to the button

Modifying the MainActivity controller: 1.- The finish () method


public void finish(View view) { 2.- The onDestroy() method
Log.d(tag, "finish event");
finish(); @Override
} public void onDestroy() {
super.onDestroy();
displayToast ("Bye, bye ...");
}
Android
The first project:
Adding methods to the MainActivity class

Exercise: A bit more complicated code. Look for information about


how to show the next dialog ... Before seeing the answer in the next
slide.
Android
The first project:
Adding methods to the MainActivity class

Exercise: A bit more complicated code: The answer.

MainActivity.java
public void buildDialogList (String title) {
final String[] items = { "Blanc", "Groc", "Blau"};
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle(title);
builder.setItems(items, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
displayToast ("Has triat el color " + items[which]);
}
});
builder.setNegativeButton("Cancel", null);
builder.setNeutralButton ("NO", null);
builder.create(); builder.show();
}
Android
The first project:
Adding methods to the MainActivity class

Exercise: Adding a button to show the list into the Dialog

Modifying the view: 1.- Adding a button

2.- Adding an onClick() attribute to the button

Modifying the MainActivity controller:


The finish () method

public void showDialogList(View view){


buildDialogList ("A list of colors … )
}
Android
The first project:
Getting values from the layout

Exercise: Adding a button to show the value from an EditText

<Button
android:id="@+id/button3"
android:onClick="showText"
android:text="@string/showText"
Android
The first project:
Getting values from the layout
A newBuildDialog method with 3 parameters

public void newBuildDialog (String title, String message, String textButton) {


AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle(title); builder.setMessage(message);
builder.setPositiveButton(textButton, null);
builder.create(); builder.show();
}

And a method to link the View (activity_main.xml) and the Controller


(MainActivity.java)

EditText getEditText;
public void showText(View view) {
getEditText = findViewById(R.id.myText);
String myText = getEditText.getText().toString();
newBuildDialog ("Showing a text", "You have written: ", myText);
}
MainActivity.java
Android
The first project:
Getting values from the layout
Android
The first project:
Getting values from the layout
Exercise: Add a counter about the number of times that you press
the button Show the text.
Android
The first project:
A multi language application
Android
The first project: A multi language application
Create new values resource files

strings
Android
The first project: A multi language application

Copy and paste the strings.xml content depending on the


desired language.

<resources>
<string name="app_name">La meua aplicació</ string>
<string name="hello">Hola mon en valencià!</ string>
<string name="finish">Acabar l\'aplicació?</ string>
<string name="showDialogList">Mostrar la llista de dialeg?
</string>
</resources>

<resources>
<string name="app_name">Mi aplicación</ string>
<string name="hello">Hola mundo en castellano!</ string>
<string name="finish">Acabar la aplicación?</ string>
<string name="showDialogList">Mostrar la lista de
dialogo?</ string>
</resources>
Android
The first project: A multi language application

Run the application and look for the Custom Locale option into the emulator or
mobile device.
Choose a language and run the application
Android

Layouts
Android
The User Interface: Layouts

A layout defines the visual structure for a user interface, such as the UI for an
activity or app widget. 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.
Instantiate layout elements at runtime. Your application can create View
and ViewGroup objects (and manipulate their properties) programmatically.

Some possibilities:
FrameLayout : designed to block out an area on the screen to display a
single item.
LinearLayout: arranges its children in a single column or a single row
TableLayout: arranges its children into rows and columns
GridLayout: composed of a set of infinitely thin lines that separate the
viewing area into cells
RelativeLayout: A Layout where the positions of the children can be
described in relation to each other or to the parent

Layouts.
Android
The User Interface: Layouts

A layout that organizes its Enables you to specify the Displays web pages.
children into a single location of child objects
horizontal or vertical row. relative to each other
It creates a scrollbar if the (child A to the left of child
length of the window B) or to the parent (aligned
exceeds the length of the to the top of the parent).
screen.

Layouts.
Android
The User Interface: Layouts

Layouts.
Android
The User Interface: Layouts.-
<LinearLayout
linear_layout.xml
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<EditText android:id="@+id/txtOne"
android:text="@string/text1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:inputType="text"
android:layout_weight="1" />
<EditText android:id="@+id/txtTwo"
android:text="@string/text2"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:inputType="text"
android:layout_weight="2" />
</LinearLayout>

@Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
// setContentView(R.layout.activity_main);
setContentView(R.layout.linear_layout);
displayToast ("Hello from onCreate!");
}
MainActivity.java
Android
The User Interface: Layouts.-
table_layout.xml
<TableLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content" android:layout_height="wrap_content"
android:stretchColumns="*" android:background="#000000">
<TableRow>
<TextView android:text="1.1“ android:background="#ffffff"
android:layout_margin="1dp" />
<TextView android:text="1.2“ android:background="#ffffff"
android:layout_margin="1dp" />
</TableRow>
<TableRow>
<TextView android:text="2.1" android:background="#ffffff"
android:layout_margin="1dp" />
<TextView android:text="2.2" android:background="#ffffff"
android:layout_margin="1dp" />
</TableRow>
</TableLayout>

protected void onCreate(Bundle savedInstanceState) {


super.onCreate(savedInstanceState);
// setContentView(R.layout.activity_main);
// setContentView(R.layout.linear_layout);
setContentView(R.layout.table_layout);
displayToast ( "Hello from onCreate!");
}
MainActivity.java
Android
The User Interface: Layouts.- Other layouts

Exercise.- Create the next user interfaces and make them appear in your
activity, using different layout files:

table_layout.xml linear_layout.xml my_own_layout.xml

More info: Using table layout


Android
The User Interface: Switching between layouts
1.- The View:
Add a new button to your layout in activity_main.xml and modify attributes

2.- The controller


Program the action in MainActivity.java and … that’s all!

public void changeLayout(View view) {


setContentView(R.layout.activity_main2);
}
Android
The User Interface: Switching between layouts

Exercise.- Add a new button in the second layout to come back to the first
layout… using the same changeLayout(View view) function!

activity_main.xml activity_main2.xml
Android
The User Interface: Different kind of buttons
Create a new buttons_layout.xml file

protected void onCreate(Bundle savedInstanceState) {


super.onCreate(savedInstanceState);
setContentView(R.layout.buttons_layout);
} MainActivity.java

Add some pictures to your drawable folder

Using a LinearLayout add


buttons and image buttons to
your layout
Android
The User Interface: Toggle Buttons.-
Add a toggle button into your layout
buttons_layout.xml
<ToggleButton
android:id="@+id/toggleButton"
android:layout_width="match_parent"
android:layout_height="68dp"
android:text="ToggleButton Delete this line
android:textOff="@string/off"
android:textOn="@string/on" Add these lines
/>
Android
The User Interface: Buttons ON/OFF

Layouts: xml files.- The View Classes: java files.- The Controller
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android" // 1.- Declaring objects
xmlns:app="http://schemas.android.com/apk/res-auto" Button myButtonONOFF;
android:layout_width="match_parent" ImageButton myImageButtonONOFF;
android:layout_height="match_parent"
android:orientation="vertical"> protected void onCreate(Bundle savedInstanceState) {
<Button super.onCreate(savedInstanceState);
android:id="@+id/buttonONOFF" setContentView(R.layout.buttons_on_off_layout);
android:layout_width="match_parent" // 2.- Linking objects with their view
android:layout_height="wrap_content“ myButtonONOFF = findViewById(R.id.buttonONOFF);
android:onClick="switchButton" myImageButtonONOFF =
findViewById(R.id.imageButtonONOFF);
android:text="@string/buttonON" />
}
<ImageButton // 3.- Switching button values
android:id="@+id/imageButtonONOFF" Boolean buttonON = true;
android:layout_width="match_parent" public void switchButton(View view) {
android:layout_height="wrap_content" if (buttonON) {
app:srcCompat="@drawable/on" /> myButtonONOFF.setText (R.string.off);
</LinearLayout> buttonON = false;
}
else {
myButtonONOFF.setText(R.string.on);
buttonON = true;
}
}

MainActivity.java
Android
The User Interface: Buttons ON/OFF
Create a new buttons_on_off_layout.xml file

protected void onCreate(Bundle savedInstanceState) {


super.onCreate(savedInstanceState);
setContentView(R.layout.buttons_on_off_layout);
}
MainActivity.java
Android
The User Interface: ImageButtons ON/OFF

Exercise: Switch the images of the ImageButton clicking on it

MainActivity.java
// 4.- Switching image button values
Boolean imageButtonON = true;
public void switchImageButton(View view) {
// TODO
// To change the image content you need to use
// myImageButtonONOFF.setImageResource(int resID)
// instead of:
// myButtonONOFF.setText (int resID);
}
Android
The User Interface: ToggleButton and listeners

A bit more complicated example: Adding a listener to the ToggleButton

// 1.- Declaring objects


MainActivity.java
Button myButtonONOFF;
ImageButton myImageButtonONOFF;
ToggleButton myToggleButton;

protected void onCreate(Bundle savedInstanceState) {


super.onCreate(savedInstanceState);
// setContentView(R.layout.activity_main);
// setContentView(R.layout.linear_layout);
setContentView(R.layout.buttons_on_off_layout);
//displayToast ("Hello from onCreate!");
// buildDialogJoan ("Títol", R.string.hello);
// 2.- Linking objects with their view
myButtonONOFF = findViewById(R.id.buttonONOFF);
myImageButtonONOFF = findViewById(R.id.imageButtonONOFF);
myToggleButton = findViewById(R.id.toggleButton);
// The listener
myToggleButton.setOnCheckedChangeListener(
new CompoundButton.OnCheckedChangeListener() {
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked) {
displayToast ("Enabled!");
} else {
displayToast ("Disabled!");
}
}
});
}
Android

CheckBoxes and
RadioButtons.
Android
The User Interface: CheckBoxes.
Create a new activity

<activity android:name=".Main2Activity"></activity>

<activity android:name=".Main2Activity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER"/>
</intent-filter>
</activity>
<activity android:name=".MainActivity"> </activity>
Android
The User Interface: CheckBoxes.
Checkboxes allow the user to select one or more options from a set of elements.
activity_main2.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<CheckBox android:id="@+id/checkbox_meat"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/meat"
<CheckBox android:id="@+id/checkbox_fish"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/fish"
</LinearLayout>

<string name="meat">Meat</string>
<string name="fish">Fish</string>
Android
The User Interface: CheckBoxes.
Adding events to our Checkboxes. The view
activity_main2.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<CheckBox android:id="@+id/checkbox_meat"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/meat"
android:onClick="onCheckboxClicked"/>
<CheckBox android:id="@+id/checkbox_fish"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/fish"
android:onClick="onCheckboxClicked"/>
</LinearLayout>
Android
The User Interface: CheckBoxes.

Adding events to our Checkboxes. The controller

public void onCheckboxClicked (View view) { Main2Activity.java


// Is the view now checked?
boolean checked = ((CheckBox) view).isChecked();
// Using an only one if
String text = ((CheckBox) view).getText().toString();
if (checked) displayToast ("Seleccionat l'element: " + text);
else displayToast ("Deseleccionat l'element: " + text);
}
Android
The User Interface: RadioButtons.
Radio buttons:
Modify the project adding a radio button group to the previous layout and
allowing the user to select ONLY ONE option from a set.
Android

The User Interface: Switching layouts using RadioButtons.

Exercise.- Add a new RadioGroup with two or more RadioButtons. Use


each one of them to switch to a different layout.
Android

WebViews
Android
The User Interface: The view WebView

The WebView class is an extension of Android's View class that allows you to
display web pages as a part of your activity layout. It does not include any
features of a fully developed web browser, such as navigation controls or an
address bar.
In order to load a web url into the WebView, you need to call a method
loadUrl(String url) of the WebView class, specifying the required url.

activity_main.xml
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<WebView
android:id="@+id/webkit"
android:layout_width="fill_parent"
android:layout_height="fill_parent" />
</LinearLayout>

More information:
WebView
Android
The User Interface: The view WebView
MainActivity.java
public class MainActivity extends AppCompatActivity {
WebView navegador;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//1.- Browsing a web page INTO the project
navegador = findViewById(R.id.webkit);
navegador.setWebViewClient(new WebViewClient());
navegador.getSettings().setJavaScriptEnabled(true);
navegador.loadUrl("https://elpais.com/");
}
}
Add a uses-permission tag into your Android Manifest file

<uses-permission
android:name="android.permission.INTERNET" />
<application …..
<!– Other tags -->
</application>
AndroidManifest.xml

One example
Android
The User Interface: WebView with an Intent
MainActivity.java
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//2.- Calling a browser OUTSIDE the project
Intent intent = new Intent(Intent.ACTION_VIEW);
Uri uri = Uri.parse ("http://www.7towns4europe.eu");
intent.setData(uri);
startActivity(intent);
}
}
activity_main.xml
<!—You don’t need anything special here 🡪
Android
The User Interface: WebView with off-line web pages
Accessing
Accessingtotooff-line
offline web pages.
web pages. 1.- Create an assets folder
Android
The User Interface: WebView with off-line web pages
Accessing
Accessingtotooff-line
offline web pages.
web pages.

MainActivity.java
public class MainActivity extends Activity {
WebView navegador;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
navegador = (WebView) findViewById(R.id.webkit);
navegador.setWebViewClient(new WebViewClient());
navegador.getSettings().setJavaScriptEnabled(true);
navegador.loadUrl("file:///android_asset/hola.html");
}
}
Android
The User Interface: WebViews and ProgressBar

Accessing to off-line web


Adding a Progress Barpages.
to the application

activity_main.xml
<android.support.constraint.ConstraintLayout
<!– Other tags 🡪
<ProgressBar
android:id="@+id/barraProgres"
<!– Other tags 🡪
/>
<WebView
android:id="@+id/webkit"
<!– Other tags 🡪
/>
</android.support.constraint.ConstraintLayout>

Access to the complete project here


Android
The User Interface: WebViews and ProgressBar
Adding a Progress Bar to the application
Instead of adding constraints to every view as you place them in the layout, you
can move each view into the positions you desire, and then click Infer
Constraints to automatically create constraints.

More info:
Build a Responsive UI with ConstraintLayout
Android
The User Interface: WebViews and ProgressBar
Adding a Progress Bar (horizontal) to the application
public class MainActivity extends AppCompatActivity { MainActivity.java
WebView navegador;
ProgressBar barraProgres;
protected void onCreate (Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
navegador = (WebView) findViewById(R.id.webkit);
barraProgres = (ProgressBar) findViewById(R.id.barraProgres);
navegador.loadUrl("http://www.elpais.es");
barraProgres.setVisibility(View.VISIBLE);

// Check the program and then add the next code


navegador.setWebChromeClient(new WebChromeClient() {
//Tell the host application the current progress of loading a page
public void onProgressChanged(WebView view, int currentProgres) {
barraProgres.incrementProgressBy(currentProgres);
if (currentProgres == 100) {
barraProgres.setVisibility(View.GONE);
}
More info:
}
}); Web Chrome Client
} // onCreate
Android
The User Interface: WebViews and ProgressBar

Accessing to off-line
Exercise: Addweb pages.
a Progress Bar and an EditText to the application.
Do something similar to the previous exercise but showing a
ProgressBar
Content_main.xml
<WebView>
<!– Other attributes 🡪
<ProgressBar
<!– Other attributes 🡪
/>
<TextView
<!– Other attributes 🡪
/>
</WebView>
Android
The User Interface: WebViews and ProgressBar
Exercise: Add a Progress Bar and an EditText to the application. Do
something similar to the previous exercise but showing a ProgressBar

// The declaration of the objects MainActivity.java


WebView navegador;
ProgressBar barraProgres;
TextView textBarraProgres;

// The view for the objects (control)


barraProgres = (ProgressBar) findViewById(R.id.progressBar);
barraProgres.setVisibility(View.VISIBLE);
textBarraProgres = (TextView) findViewById(R.id.textView);
// The listener
navegador.setWebChromeClient(new WebChromeClient() {
//Tell the host application the current progress of loading a page
public void onProgressChanged(WebView view, int currentProgres) {
barraProgres.incrementProgressBy(currentProgres);
if (currentProgres == 100) {
barraProgres.setVisibility(View.GONE);
textBarraProgres.setVisibility(View.INVISIBLE);
}
}
});
Android

ListViews and Adapters

Get the complete project here


Android
The User Interface: ListViews.
ListView is a view group that displays a list of scrollable items. The list
items are automatically inserted to the list using an Adapter that pulls content
from a source such as an array or database query and converts each item
result into a view that's placed into the list.

Steps to create a ListView after creating a new project using an empty


activity:
1.- A layout to display the ListView to the user.
2.- A empty activity that shows and control it.
3.- An adapter to fill each element of the ListView.

activity_main.xml
1.- A layout to display the ListView to the user
<androidx.constraintlayout.widget.ConstraintLayout
<!– Other tags 🡪
<ListView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/lstOptions"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
<!– Other attributes ->
/>
Andrid
The User Interface: ListViews and Adapters

Adapter: An Adapter object acts as a bridge between an AdapterView and the


underlying data for that view. The Adapter provides access to the data items. The
Adapter is also responsible for making a View for each item in the data set.

Options Adapter lstInfo

SimpleAdapter Tutorial
More info about Adapters and ArrayAdapters:
Android
A new project: My adapters
Android
A new project: My adapters
Android
The first way: A built-in adapter in a new empty activity

SimplestAdapterActivity.java
Android
The first way: The ListView layout
activity_simplest_adapter.xml

<ListView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/lstOptions"
<!– Other attributes ->
/>
Android
The first way: The code

The elements to be shown

private private static ArrayList<String> Llibres = new ArrayList<>();


String[] llibres =
{"El ninot de neu", "Senyoria", "Els assassins de l'emperador"};

The built-in adapter


ArrayAdapter<String> adapter =
new ArrayAdapter<String>
(this, android.R.layout.simple_list_item_1, llibres);

The ListView object

private ListView myListView;


myListView = findViewById (R.id.lstOptions);
myListView.setAdapter(adapter);
Android
The first way: The code
SimplestAdapterActivity.java
public class SimplestAdapterActivity extends AppCompatActivity
{
// Data Source
private String[] llibres = {"El ninot de neu", "Senyoria", "Els assassins de l'emperador"};
// The View object
private ListView myListView;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_simplest_adapter);
// The Adapter
ArrayAdapter<String> adapter =
new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, llibres);
// The View
myListView = findViewById (R.id.lstOptions);
myListView.setAdapter(adapter);
}
}
Android
The first way: A built-in adapter

Try to use another layouts to show the options in a ListView:


Android
The first way: A built-in adapter
Add a listener to select / unselect books
public class SimplestAdapterActivity extends MainMenu {
// Data Source
private String[] llibres = {"El ninot de neu" , "Senyoria" , "Els assassins de l'emperador" };
// The View object
private ListView myListView ;

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

// The Adapter
ArrayAdapter <String> adapter =
new ArrayAdapter<>( this, android.R .layout.simple_list_item_multiple_choice, llibres);
// The View
myListView = findViewById ( R.id.lstOptions);
myListView .setAdapter( adapter);

// To let select / unselect checkboxes


myListView .setChoiceMode( ListView .CHOICE_MODE_MULTIPLE);
myListView .setOnItemClickListener( new AdapterView .OnItemClickListener () {
@Override
public void onItemClick (AdapterView <?> parent, View view, int position, long id) {
Log.i("SimplestAdapterActivity" , "onItemClick: " + position);
CheckedTextView v = (CheckedTextView ) view;
boolean currentCheck = v.isChecked();
}
});

}
}
Android
The first way: A built-in adapter
Add a listener to select / unselect books
Android
Second way: Using a handmade layout
Android
Second way: The ListView layout

<ListView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/lstOptions2"
<!– Other attributes ->
/>
Android
Second way: The handmade layout
Android
Second way: The code

The elements to be shown


private String[] llibres =
{"El ninot de neu", "Senyoria", "Els assassins de l'emperador"};

The adapter
ArrayAdapter<String> adapter = new ArrayAdapter<>
(this, // The context
R.layout.activity_my_book, // The handmade layout
R.id.bookName, // The id where when show the title of the book
llibres // The array of titles
);

The ListView object and variables

private ListView myBooks;


myBooks = findViewById(R.id.lstOptions2);
myBooks.setAdapter(adapter);
Android
Second way: The code

public class HandmadeLayoutActivity extends AppCompatActivity {

private String[] llibres = {


"El ninot de neu", "Senyoria", "Els assassins de l'emperador"};
private ListView myBooks;

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

// The Adapter
ArrayAdapter<String> adapter = new ArrayAdapter<>
(this, R.layout.activity_my_book, R.id.bookName, llibres );
// The View
myBooks = findViewById(R.id.lstOptions2);
myBooks.setAdapter(adapter);

}
}
Android
Using a handmade layout. The result
Android
Using a handmade layout: Adding a listener

protected void onCreate(Bundle savedInstanceState) {


super.onCreate(savedInstanceState);
setContentView(R.layout.activity_handmade_layout);

// The Adapter
ArrayAdapter<String> adapter = new ArrayAdapter<>
(this, R.layout.activity_my_book, R.id.bookName, llibres);
// The View
myBooks = findViewById(R.id.lstOptions2);
myBooks.setAdapter(adapter);
// The listener
myBooks.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
String bookName = llibres[position];
buildDialog ("My books", " Book name: " + bookName, HandmadeLayoutActivity.this);
}
});
}
Android
Using a handmade layout: Adding a listener
Android
Third way: Using a SimpleAdapter class
Android
Third way: Using a SimpleAdapter class

<ListView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/lstWriters"
<!– Other attributes ->
/>
Android
Third way: Using a SimpleAdapter class
Android
Third way: The code

The ListView object and variables

private String[] names =


{"Jaume Cabré", "John Grisman", "Santiago Posteguillo"};
private int[] photosWriters =
{R.drawable.jaume_cabre, R.drawable.john_grisham, R.drawable.santiago_posteguillo};
private ListView myWriters;

Creating a HashMap (name, picture)

List<Map<String ,Object>> data = new ArrayList<Map<String , Object>>();


for (int i = 0; i < 3; i++) {
Map<String ,Object> datum = new HashMap<String ,Object>();
datum.put("photo", photosWriters[i]);
datum.put("name", names[i]);
data.add(datum);
}
myWriters = findViewById(R.id.lstWriters);

More information about SimpleAdapter here


Simple Adapter Tutorial With Example here
Android
Third way: Using a SimpleAdapter class

The adapter

SimpleAdapter simpleAdapter =
new SimpleAdapter(
this,
data,
R.layout.activity_my_writer,
new String[] {"photo","name"},
new int[] {R.id.writerPhoto, R.id.writerName}
);
myWriters.setAdapter(simpleAdapter);

More information about SimpleAdapter here


Simple Adapter Tutorial With Example here
Android
Third way: Using a SimpleAdapter class
ASimpleAdapterActivity.java
public class ASimpleAdapterActivity
extends AppCompatActivity {
private String[] names =
{"Jaume Cabré", "John Grisman", "Santiago Posteguillo"};
private int[] photosWriters =
{R.drawable.jaume_cabre, R.drawable.john_grisham, R.drawable.santiago_posteguillo};
private ListView myWriters;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_a_simple_adapter);
// Creating an array <Name writer, Photo writer>
List<Map<String ,Object>> data = new ArrayList<Map<String , Object>>();
for (int i = 0; i < 3; i++) {
Map<String ,Object> datum = new HashMap<String ,Object>();
datum.put("photo", photosWriters[i]);
datum.put("name", names[i]);
data.add(datum);
}
myWriters = findViewById(R.id.lstWriters);
// The SimpleAdapter class
SimpleAdapter simpleAdapter =
new SimpleAdapter(
this, data, R.layout.activity_my_writer,
new String[] {"photo","name"}, new int[] {R.id.writerPhoto, R.id.writerName}
);
myWriters.setAdapter(simpleAdapter);
}
}
Android
Third way: Using a SimpleAdapter class
Android
Third way: Using a SimpleAdapter class

Exercise: Add a listener to show the selected writer’s name using a


Toast or AlertDialog object.
Android
Third way: Using a SimpleAdapter class

Exercise:
Add one book and photo per each writer. Then when you click on
the writer show the picture and name of the book

You might also like