Android 1 Introduction
Android 1 Introduction
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.
There are three types of projects, and they all share the same
general structure but differ in function:
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.
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout. activity_main);
}
} 2.- Establishing the user interface
<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
<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>
Activity lifecycle
Activity reference
Android
The first project:
Adding methods to the MainActivity class
Log.d
Android
The first project:
Adding methods to the MainActivity class
@Override
public void onStart() {
super.onStart();
displayToast( "onStart() event");
buildDialog ("onStart() action", "Starting ...");
}
Android
The first project:
Adding methods to the MainActivity class
AlertDialog
AlertBuilder Reference
AlertDialog exemple
Android
The first project:
Adding methods to the MainActivity class
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?
Exercise: What are the values of which in the other two buttons?
Android
The first project:
Adding methods to the MainActivity class
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
<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
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
<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>
Exercise.- Create the next user interfaces and make them appear in your
activity, using different layout files:
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
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
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
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.
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
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>
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);
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
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
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
@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
@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);
}
}
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 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
);
@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
// 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 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);
Exercise:
Add one book and photo per each writer. Then when you click on
the writer show the picture and name of the book