Android App Development: Six Weeks Summer Training On
Android App Development: Six Weeks Summer Training On
REPORT
On
Submitted by:
TARUN SHARMA
Roll no. : 252001003
Department : ECE A
Submitted to:
1
Certificate
2
ACKNOWLEDGEMENT
What is Kotlin?
Kotlin is a modern, trending programming language that was released
in 2016 by JetBrains.
3
It has become very popular since it is compatible with J (one of the
most popular programming languages out there), which means that
Java code (and libraries) can be used in Kotlin programs.
Kotlin Syntax
In the previous chapter, we created a Kotlin file called Main.kt, and we
used the following code to print "Hello World" to the screen:
Example
fun main() {
println("Hello World")
}
4
Example explained
For example, the println() function is inside the main() function, meaning
that this will be executed. The println() function is used to output/print
text, and in our example it will output "Hello World".
Main Parameters
Before Kotlin version 1.3, it was required to use the main() function
with parameters, like: fun main(args : Array<String>). The example above
had to be written like this to work:
Example
fun main(args : Array<String>) {
println("Hello World")
}
Note: This is no longer required, and the program will run fine without it.
However, it will not do any harm if We have been using it in the past, and will
continue to use it.
5
Kotlin Output (Print)
The println() function is used to output values/print text:
Example
fun main() {
println("Hello World")
}
Example
fun main() {
println("Hello World!")
println("I am learning Kotlin.")
println("It is awesome!")
}
Example
fun main() {
println(3 + 3)
}
Example
fun main() {
print("Hello World! ")
print("I am learning Kotlin. ")
6
print("It is awesome!")
}
Kotlin Comments
Comments can be used to explain Kotlin code, and to make it more
readable. It can also be used to prevent execution when testing
alternative code.
Single-line Comments
Single-line comments starts with two forward slashes (//).
Any text between // and the end of the line is ignored by Kotlin (will
not be executed).
Example
// This is a comment
println("Hello World")
Example
println("Hello World") // This is a comment
7
Multi-line Comments
Multi-line comments start with /* and ends with */.
Example
/* The code below will print the words Hello World
to the screen, and it is amazing */
println("Hello World")
Kotlin Variables
Variables are containers for storing data values.
To create a variable, use var or val, and assign a value to it with the
equal sign (=):
Syntax
var variableName = value
val variableName = value
Example
var name = "John"
val birthyear = 1975
The difference between var and val is that variables declared with the
var keyword can be changed/modified, while val variables cannot.
8
Variable Type
Unlike many other programming languages, variables in Kotlin do not
need to be declared with a specified type (like "String" for text or
"Int" for numbers, if We are familiar with those).
To create a variable in Kotlin that should store text and another that
should store a number, look at the following example:
Example
var name = "John" // String (text)
val birthyear = 1975 // Int (number)
Example
var name: String = "John" // String
val birthyear: Int = 1975 // Int
println(name)
println(birthyear)
Example
9
var name: String
name = "John"
println(name)
Example
Note: We will learn more about Data Types in the next chapter.
Notes on val
When We create a variable with the val keyword, the value cannot be
changed/reassigned.
Example
val name = "John"
name = "Robert" // Error (Val cannot be reassigned)
println(name)
Example
var name = "John"
name = "Robert"
println(name)
So When To Use val?
10
Example
val pi = 3.14159265359
println(pi)
Display Variables
Like We have seen with the examples above, the println() method is
often used to display variables.
Example
val name = "John"
println("Hello " + name)
Example
val firstName = "John "
val lastName = "Doe"
val fullName = firstName + lastName
println(fullName)
Example
val x = 5
val y = 6
println(x + y) // Print the value of x + y
11
Variable Names
A variable can have a short name (like x and y) or more descriptive
names (age, sum, totalVolume).
camelCase variables
Example
val myNum = 5 // Int
val myDoubleNum = 5.99 // Double
val myLetter = 'D' // Char
12
val myBoolean = true // Boolean
val myText = "Hello" // String
Example
val myNum: Int = 5 // Int
val myDoubleNum: Double = 5.99 // Double
val myLetter: Char = 'D' // Char
val myBoolean: Boolean = true // Boolean
val myText: String = "Hello" // String
We will learn more about when We need to specify the type later.
Numbers
Number types are divided into two groups:
13
If We don't specify the type for a numeric variable, it is most often
returned as Int for whole numbers and Double for floating point
numbers.
Integer Types
Byte
The Byte data type can store whole numbers from -128 to 127. This
can be used instead of Int or other integer types to save memory when
We are certain that the value will be within -128 and 127:
Example
val myNum: Byte = 100
println(myNum)
Short
The Short data type can store whole numbers from -32768 to 32767:
Example
val myNum: Short = 5000
println(myNum)
Int
The Int data type can store whole numbers from -2147483648 to
2147483647:
Example
val myNum: Int = 100000
println(myNum)
Long
14
when Int is not large enough to store the value. Optionally, We can
end the value with an "L":
Example
val myNum: Long = 15000000000L
println(myNum)
Example
val myNum1 = 2147483647 // Int
val myNum2 = 2147483648 // Long
Float
The Float data type can store fractional numbers from 3.4e−038 to
3.4e+038. Note that We should end the value with an "F":
Example
val myNum: Float = 5.75F
println(myNum)
Double
The Double data type can store fractional numbers from 1.7e−308 to
1.7e+038:
15
Example
val myNum: Double = 19.99
println(myNum)
The precision of a floating point value indicates how many digits the
value can have after the decimal point. The precision of Float is only
six or seven decimal digits, while Double variables have a precision of
about 15 digits. Therefore it is safer to use Double for most
calculations.
Scientific Numbers
Example
val myNum1: Float = 35E3F
val myNum2: Double = 12E4
println(myNum1)
println(myNum2)
Booleans
The Boolean data type and can only take the values true or false:
Example
val isKotlinFun: Boolean = true
val isFishTasty: Boolean = false
println(isKotlinFun) // Outputs true
println(isFishTasty) // Outputs false
16
Characters
The Char data type is used to store a single character. A char value
must be surrounded by single quotes, like 'A' or 'c':
Example
val myGrade: Char = 'B'
println(myGrade)
Example
val myLetter: Char = 66
println(myLetter) // Error
Strings
The String data type is used to store a sequence of characters (text).
String values must be surrounded by double quotes:
Example
val myText: String = "Hello World"
println(myText)
Arrays
Arrays are used to store multiple values in a single variable, instead of
declaring separate variables for each value.
17
Type Conversion
Type conversion is when We convert the value of one data type to
another type.
Example
val x: Int = 5
val y: Long = x
println(y) // Error: Type mismatch
Example
val x: Int = 5
val y: Long = x.toLong()
println(y)
Kotlin Operators
Operators are used to perform operations on variables and values.
18
Operand Operator Operand
100 + 50
In the example below, the numbers 100 and 50 are operands, and the
+ sign is an operator:
Example
var x = 100 + 50
Although the + operator is often used to add together two values, like
in the example above, it can also be used to add together a variable
and a value, or a variable and a variable:
Example
var sum1 = 100 + 50 // 150 (100 + 50)
var sum2 = sum1 + 250 // 400 (150 + 250)
var sum3 = sum2 + sum2 // 800 (400 + 400)
Arithmetic Operators
Arithmetic operators are used to perform common mathematical
operations.
Operator Name Description Example
+ Addition Adds together two values x+y
- Subtraction Subtracts one value from another x - y
* Multiplication Multiplies two values x*y
19
/ Division Divides one value from another x/y
% Modulus Returns the division remainder x%y
++ Increment Increases the value by 1 ++x
-- Decrement Decreases the value by 1 --x
Example
var x = 10
Example
var x = 10
x += 5
20
Kotlin Comparison Operators
Comparison operators are used to compare two values, and returns a
Boolean value: either true or false.
We will learn much more about Booleans in the Boolean chapter and
Conditions.
Kotlin Strings
Strings are used for storing text.
Example
var greeting = "Hello"
21
Unlike Java, We do not have to specify that the variable should be a
String. Kotlin is smart enough to understand that the greeting variable
in the example above is a String because of the double quotes.
However, just like with other data types, We can specify the type if
We insist:
Example
var greeting: String = "Hello"
Example
Access a String
To access the characters (elements) of a string, We must refer to the
index number inside square brackets.
String indexes start with 0. In the example below, we access the first
and third element in txt:
22
Example
var txt = "Hello World"
println(txt[0]) // first element (H)
println(txt[2]) // third element (l)
[0] is the first element. [1] is the second element, [2] is the third
element, etc.
String Length
A String in Kotlin is an object, which contain properties and functions
that can perform certain operations on strings, by writing a dot
character (.) after the specific string variable. For example, the length
of a string can be found with the length property:
Example
var txt = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
println("The length of the txt string is: " + txt.length)
String Functions
There are many string functions available, for example toUpperCase()
and toLoourCase():
Example
var txt = "Hello World"
println(txt.toUpperCase()) // Outputs "HELLO WORLD"
println(txt.toLoourCase()) // Outputs "hello world"
Comparing Strings
The compareTo(string) function compares two strings and returns 0 if both
are equal:
23
Example
var txt1 = "Hello World"
var txt2 = "Hello World"
println(txt1.compareTo(txt2)) // Outputs 0 (they are equal)
Example
var txt = "Please locate where 'locate' occurs!"
println(txt.indexOf("locate")) // Outputs 7
Example
var txt1 = "It's alright"
var txt2 = "That's great"
String Concatenation
The + operator can be used between strings to add them together to
make a new string. This is called concatenation:
24
Example
var firstName = "John"
var lastName = "Doe"
println(firstName + " " + lastName)
Note that we have added an empty text (" ") to create a space between
firstName and lastName on print.
Example
var firstName = "John "
var lastName = "Doe"
println(firstName.plus(lastName))
String Templates/Interpolation
Instead of concatenation, We can also use "string templates", which
is an easy way to add variables and expressions inside a string.
Example
var firstName = "John"
var lastName = "Doe"
println("My name is $firstName $lastName")
Kotlin Booleans
25
Very often, in programming, We will need a data type that can only
have one of two values, like:
YES / NO
ON / OFF
TRUE / FALSE
For this, Kotlin has a Boolean data type, which can take the values true
or false.
Boolean Values
A boolean type can be declared with the Boolean keyword and can only
take the values true or false:
Example
val isKotlinFun: Boolean = true
val isFishTasty: Boolean = false
println(isKotlinFun) // Outputs true
println(isFishTasty) // Outputs false
Just like We have learned with other data types in the previous
chapters, the example above can also be written without specifying
the type, as Kotlin is smart enough to understand that the variables are
Booleans:
Example
val isKotlinFun = true
val isFishTasty = false
println(isKotlinFun) // Outputs true
println(isFishTasty) // Outputs false
Boolean Expression
A Boolean expression returns a Boolean value: true or false.
26
We can use a comparison operator, such as the greater than (>)
operator to find out if an expression (or a variable) is true:
Example
val x = 10
val y = 9
println(x > y) // Returns true, because 10 is greater than 9
Or even easier:
Example
println(10 > 9) // Returns true, because 10 is greater than 9
Example
val x = 10;
println(x == 10); // Returns true, because the value of x is equal to 10
Example
println(10 == 15); // Returns false, because 10 is not equal to 15
27
Less than: a < b
Less than or equal to: a <= b
Greater than: a > b
Greater than or equal to: a >= b
Equal to a == b
Not Equal to: a != b
Kotlin if
Use if to specify a block of code to be executed if a condition is true.
Syntax
if (condition) {
// block of code to be executed if the condition is true
}
Example
val x = 20
val y = 18
if (x > y) {
println("x is greater than y")
}
Example explained
Kotlin else
Use else to specify a block of code to be executed if the condition is
false.
Syntax
if (condition) {
// block of code to be executed if the condition is true
} else {
// block of code to be executed if the condition is false
}
Example
val time = 20
if (time < 18) {
println("Good day.")
29
} else {
println("Good evening.")
}
// Outputs "Good evening."
Example explained
In the example above, time (20) is greater than 18, so the condition is
false, so we move on to the else condition and print to the screen "Good
evening". If the time was less than 18, the program would print "Good
day".
Kotlin else if
Use else if to specify a new condition if the first condition is false.
Syntax
if (condition1) {
// block of code to be executed if condition1 is true
} else if (condition2) {
// block of code to be executed if the condition1 is false and condition2 is true
} else {
// block of code to be executed if the condition1 is false and condition2 is false
}
Example
val time = 22
if (time < 10) {
println("Good morning.")
} else if (time < 20) {
println("Good day.")
} else {
println("Good evening.")
}
// Outputs "Good evening."
30
Example explained
In the example above, time (22) is greater than 10, so the first
condition is false. The next condition, in the else if statement, is also
false, so we move on to the else condition since condition1 and
condition2 is both false - and print to the screen "Good evening".
However, if the time was 14, our program would print "Good day."
Example
val time = 20
val greeting = if (time < 18) {
"Good day."
} else {
"Good evening."
}
println(greeting)
Note: We can ommit the curly braces {} when if has only one
statement:
Example
fun main() {
val time = 20
val greeting = if (time < 18) "Good day." else "Good evening."
println(greeting)
}
Tip: This example is similar to the "ternary operator" (short hand if...else) in
Java.
31
Kotlin when
Instead of writing many if..else expressions, We can use the when
expression, which is much easier to read.
Example
Loops
Loops can execute a block of code as long as a specified condition is
reached.
Loops are handy because they save time, reduce errors, and they make
code more readable.
Syntax
while (condition) {
// code block to be executed
}
In the example below, the code in the loop will run, over and over
again, as long as the counter variable (i) is less than 5:
33
Example
var i = 0
while (i < 5) {
println(i)
i++
}
Syntax
do {
// code block to be executed
}
while (condition);
The example below uses a do/while loop. The loop will always be
executed at least once, even if the condition is false, because the code
block is executed before the condition is tested:
Example
var i = 0
do {
println(i)
i++
}
while (i < 5)
Example
var i = 0
while (i < 10) {
println(i)
i++
if (i == 4) {
break
}
}
Kotlin Continue
The continue statement breaks one iteration (in the loop), if a specified
condition occurs, and continues with the next iteration in the loop.
Kotlin Arrays
Arrays are used to store multiple values in a single variable, instead of
creating separate variables for each value.
To create an array, use the arrayOf() function, and place the values in a
comma-separated list inside it:
val cars = arrayOf("Volvo", "BMW", "Ford", "Mazda")
Example
val cars = arrayOf("Volvo", "BMW", "Ford", "Mazda")
println(cars[0])
// Outputs Volvo
Note: Just like with Strings, Array indexes start with 0: [0] is the first
element. [1] is the second element, etc.
36
Change an Array Element
To change the value of a specific element, refer to the index number:
Example
cars[0] = "Opel"
Example
val cars = arrayOf("Volvo", "BMW", "Ford", "Mazda")
cars[0] = "Opel"
println(cars[0])
// Now outputs Opel instead of Volvo
Example
val cars = arrayOf("Volvo", "BMW", "Ford", "Mazda")
println(cars.size)
// Outputs 4
Example
val cars = arrayOf("Volvo", "BMW", "Ford", "Mazda")
if ("Volvo" in cars) {
println("It exists!")
} else {
println("It does not exist.")
}
37
Loop Through an Array
Often when We work with arrays, We need to loop through all of the
elements.
We can loop through the array elements with the for loop, which We
will learn even more about in the next chapter.
Example
val cars = arrayOf("Volvo", "BMW", "Ford", "Mazda")
for (x in cars) {
println(x)
}
To loop through array elements, use the for loop together with the in
operator:
38
Example
Example
val nums = arrayOf(1, 5, 10, 15, 20)
for (x in nums) {
println(x)
}
In Kotlin, the for loop is used to loop through arrays, ranges, and other
things that contains a countable number of values.
We will learn more about ranges in the next chapter - which will
create a range of values.
Kotlin Ranges
With the for loop, We can also create ranges of values with "..":
39
Example
Example
for (nums in 5..15) {
println(nums)
}
Example
val nums = arrayOf(2, 4, 6, 8)
if (2 in nums) {
println("It exists!")
} else {
println("It does not exist.")
}
Example
val cars = arrayOf("Volvo", "BMW", "Ford", "Mazda")
if ("Volvo" in cars) {
println("It exists!")
} else {
println("It does not exist.")
}
40
Break or Continue a Range
We can also use the break and continue keywords in a range/for loop:
Example
Skip the value of 10 in the loop, and continue with the next iteration:
for (nums in 5..15) {
if (nums == 10) {
continue
}
println(nums)
}
Kotlin Functions
Functions are used to perform certain actions, and they are also
known as methods.
41
Predefined Functions
So it turns out We already know what a function is. We have been
using it the whole time through this tutorial!
Example
fun main() {
println("Hello World")
}
Example
Call a Function
Now that We have created a function, We can execute it by calling
it.
42
In the following example, myFunction() will print some text (the action),
when it is called:
Example
fun main() {
myFunction() // Call myFunction
}
Example
fun main() {
myFunction()
myFunction()
myFunction()
}
Function Parameters
Information can be passed to functions as parameter.
The following example has a function that takes a String called fname
as parameter. When the function is called, we pass along a first name,
which is used inside the function to print the full name:
43
Example
fun myFunction(fname: String) {
println(fname + " Doe")
}
fun main() {
myFunction("John")
myFunction("Jane")
myFunction("George")
}
// John Doe
// Jane Doe
// George Doe
Multiple Parameters
We can have as many parameters as We like:
Example
fun myFunction(fname: String, age: Int) {
println(fname + " is " + age)
}
fun main() {
myFunction("John", 35)
myFunction("Jane", 32)
myFunction("George", 15)
}
// John is 35
44
// Jane is 32
// George is 15
Note: When working with multiple parameters, the function call must
have the same number of arguments as there are parameters, and the
arguments must be passed in the same order.
Return Values
In the examples above, we used functions to output a value. In the
following example, we will use a function to return a value and
assign it to a variable.
To return a value, use the return keyword, and specify the return type
after the function's parantheses (Int in this example):
Example
fun main() {
var result = myFunction(3)
println(result)
}
// 8 (3 + 5)
Example
45
fun myFunction(x: Int, y: Int): Int {
return (x + y)
}
fun main() {
var result = myFunction(3, 5)
println(result)
}
// 8 (3 + 5)
Example
fun myFunction(x: Int, y: Int) = x + y
fun main() {
var result = myFunction(3, 5)
println(result)
}
// 8 (3 + 5)
46
Procedural programming is about writing procedures or methods that
perform operations on the data, while object-oriented programming is
about creating objects that contain both data and methods.
class
Fruit
objects
Apple
Banana
Mango
47
Another example:
class
Car
objects
Volvo
Audi
Toyota
When the individual objects are created, they inherit all the variables
and methods from the class.
We will learn much more about classes and objects in the next
chapter.
Kotlin Classes/Objects
Everything in Kotlin is associated with classes and objects, along with
its properties and functions. For example: in real life, a car is an
object. The car has properties, such as brand, weight and color, and
functions, such as drive and brake.
48
Create a Class
To create a class, use the class keyword, and specify the name of the
class:
Example
Create a Car class along with some properties (brand, model and
year)
class Car {
var brand = ""
var model = ""
var year = 0
}
Create an Object
Now we can use the class named Car to create objects.
In the example below, we create an object of Car called c1, and then
we access the properties of c1 by using the dot syntax (.), just like we
did to access array and string properties:
Example
// Create a c1 object of the Car class
val c1 = Car()
Multiple Objects
We can create multiple objects of one class:
Example
val c1 = Car()
c1.brand = "Ford"
c1.model = "Mustang"
c1.year = 1969
val c2 = Car()
c2.brand = "BMW"
c2.model = "X5"
c2.year = 1999
println(c1.brand) // Ford
println(c2.brand) // BMW
Kotlin Constructor
In the previous chapter, we created an object of a class, and specified
the properties inside the class, like this:
50
Example
class Car {
var brand = ""
var model = ""
var year = 0
}
fun main() {
val c1 = Car()
c1.brand = "Ford"
c1.model = "Mustang"
c1.year = 1969
}
Example
class Car(var brand: String, var model: String, var year: Int)
fun main() {
val c1 = Car("Ford", "Mustang", 1969)
}
Example
class Car(var brand: String, var model: String, var year: Int)
fun main() {
51
val c1 = Car("Ford", "Mustang", 1969)
val c2 = Car("BMW", "X5", 1999)
val c3 = Car("Tesla", "Model S", 2020)
}
Introduction to SQL
What is SQL?
SQL stands for Structured Query Language
SQL lets We access and manipulate databases
SQL became a standard of the American National Standards Institute
(ANSI) in 1986, and of the International Organization for Standardization
(ISO) in 1987
52
SQL is a Standard - BUT....
Although SQL is an ANSI/ISO standard, there are different versions
of the SQL language.
Note: Most of the SQL database programs also have their own
proprietary extensions in addition to the SQL standard!
RDBMS
RDBMS stands for Relational Database Management System.
RDBMS is the basis for SQL, and for all modern database systems
such as MS SQL Server, IBM DB2, Oracle, MySQL, and Microsoft
Access.
53
Example
SELECT * FROM Customers;
Every table is broken up into smaller entities called fields. The fields
in the Customers table consist of CustomerID, CustomerName,
ContactName, Address, City, PostalCode and Country. A field is a
column in a table that is designed to maintain specific information
about every record in the table.
SELECT Syntax
SELECT column1, column2, ...
FROM table_name;
Here, column1, column2, ... are the field names of the table We want
to select data from. If We want to select all the fields available in the
table, use the following syntax:
SELECT * FROM table_name;
54
SELECT Column Example
The following SQL statement selects the "CustomerName" and "City"
columns from the "Customers" table:
Example
SELECT CustomerName, City FROM Customers;
SELECT * Example
The following SQL statement selects all the columns from the
"Customers" table:
Example
SELECT * FROM Customers;
55
SELECT Example Without DISTINCT
The following SQL statement selects all (including the duplicates)
values from the "Country" column in the "Customers" table:
Example
SELECT Country FROM Customers;
Now, let us use the SELECT DISTINCT statement and see the result.
Example
SELECT DISTINCT Country FROM Customers;
56
Here is the workaround for MS Access:
Example
SELECT Count(*) AS DistinctCountries
FROM (SELECT DISTINCT Country FROM Customers);
WHERE Syntax
SELECT column1, column2, ...
FROM table_name
WHERE condition;
Example
SELECT * FROM Customers
WHERE Country='Mexico';
57
SQL requires single quotes around text values (most database systems
will also allow double quotes).
Example
SELECT * FROM Customers
WHERE CustomerID=1;
Operator Description
= Equal
> Greater than
< Less than
>= Greater than or equal
<= Less than or equal
Not equal. Note: In some versions of SQL this operator
<>
may be written as !=
BETWEEN Between a certain range
LIKE Search for a pattern
Layouts
A layout defines the structure for a user interface in your app,
such as in an activity. All elements in the layout are built using
a hierarchy of View and ViewGroup objects. A View usually draws
something the user can see and interact with. Whereas
a ViewGroup is an invisible container that defines the layout
58
structure for View and other ViewGroup objects, as shown in figure
1.
After you've declared your layout in XML, save the file with
the .xml extension, in your Android project's res/layout/ directory,
so it will properly compile.
60
More information about the syntax for a layout XML file is
available in the Layout Resources document.
Attributes
Every View and ViewGroup object supports their own variety of
XML attributes. Some attributes are specific to a View object
(for example, TextView supports the textSize attribute), but these
attributes are also inherited by any View objects that may
extend this class. Some are common to all View objects,
because they are inherited from the root View class (like
the id attribute). And, other attributes are considered "layout
parameters," which are attributes that describe certain layout
orientations of the View object, as defined by that object's
parent ViewGroup object.
61
ID
62
2. Then create an instance of the view object and capture it from the
layout (typically in the onCreate() method):
KotlinJava
val myButton: Button = findViewById(R.id.my_button)
63
Figure 2. Visualization of a view hierarchy with layout parameters associated with
each view
Note that every LayoutParams subclass has its own syntax for
setting values. Each child element must define LayoutParams
that are appropriate for its parent, though it may also define
different LayoutParams for its own children.
All view groups include a width and height
(layout_width and layout_height), and each view is required to define
them. Many LayoutParams also include optional margins and
borders.
You can specify width and height with exact measurements,
though you probably won't want to do this often. More often,
you will use one of these constants to set the width or height:
wrap_content tells your view to size itself to the dimensions
required by its content.
match_parent tells your view to become as big as its parent view
group will allow.
64
because it helps ensure that your app will display properly
across a variety of device screen sizes. The accepted
measurement types are defined in the Available
Resources document.
Layout Position
The geometry of a view is that of a rectangle. A view has a
location, expressed as a pair of left and top coordinates, and
two dimensions, expressed as a width and a height. The unit
for location and dimensions is the pixel.
It is possible to retrieve the location of a view by invoking the
methods getLeft() and getTop(). The former returns the left, or X,
coordinate of the rectangle representing the view. The latter
returns the top, or Y, coordinate of the rectangle representing
the view. These methods both return the location of the view
relative to its parent. For instance, when getLeft() returns 20, that
means the view is located 20 pixels to the right of the left edge
of its direct parent.
In addition, several convenience methods are offered to avoid
unnecessary computations, namely getRight() and getBottom().
These methods return the coordinates of the right and bottom
edges of the rectangle representing the view. For instance,
calling getRight() is similar to the following computation: getLeft() +
getWidth().
Common Layouts
Each subclass of the ViewGroup class provides a unique way to
display the views you nest within it. Below are some of the
more common layout types that are built into the Android
platform.
Note: Although you can nest one or more layouts within another layout to achieve
your UI design, you should strive to keep your layout hierarchy as shallow as
possible. Your layout draws faster if it has fewer nested layouts (a wide view
hierarchy is better than a deep view hierarchy).
66
Linear Layout
Relative Layout
Web View
67
Building Layouts with an Adapter
When the content for your layout is dynamic or not pre-
determined, you can use a layout that subclasses AdapterView to
populate the layout with views at runtime. A subclass of
the AdapterView class uses an Adapter to bind data to its layout.
The Adapter behaves as a middleman between the data source
and the AdapterView layout—the Adapter retrieves the data (from a
source such as an array or a database query) and converts
each entry into a view that can be added into
the AdapterView layout.
Common layouts backed by an adapter include:
List View
Grid View
68
Filling an adapter view with data
69
val listView: ListView = findViewById(R.id.listview)
listView.adapter = adapter
Use this adapter when your data comes from a Cursor. When
using SimpleCursorAdapter, you must specify a layout to use for each
row in the Cursor and which columns in the Cursor should be
inserted into which views of the layout. For example, if you want to
create a list of people's names and phone numbers, you can
perform a query that returns a Cursor containing a row for each
person and columns for the names and numbers. You then create
a string array specifying which columns from the Cursor you want in
the layout for each result and an integer array specifying the
corresponding views that each column should be placed:
KotlinJava
val fromColumns = arrayOf(ContactsContract.Data.DISPLAY_NAME,
ContactsContract.CommonDataKinds.Phone.NUMBER)
val toViews = intArrayOf(R.id.display_name, R.id.phone_number)
70
listView.adapter = adapter
If, during the course of your app's life, you change the
underlying data that is read by your adapter, you should
call notifyDataSetChanged(). This will notify the attached view that the
data has been changed and it should refresh itself.
Handling click events
Thank You
71