Android Tutorials - JJS
Android Tutorials - JJS
Basic Introduction
Android – Open Source & Linux Based OS for Mobile Devices, Smartphones,
Tablets, Computers et…
Android apps can be developed using Kotlin Programming Language or
Java Programming Language.
Java is a simple, powerful, and robust object-oriented programming
language suited for various purposes like Android apps, web apps, server
apps, embedded systems, big data and more.
Kotlin is a programming language that runs on a Java virtual machine
(JVM), can be compiled into JavaScript, and run-in browsers. An Android
developer can code on Kotlin/Native and use IDE to build cross-platform
apps.
Kotlin and Java provide almost the same speed for coding.
As both Kotlin and Java compile to ByteCode (which runs on JVM) it is a
daunting task to compare them when it comes to memory usage. Hence,
measuring, tracking, and comparing their performance is hard.
Android applications are usually developed in Java language using android
software development kit.
Syntax :
1. Variables :
int rollnumber = 3;
char name = 'X';
float income = 500.36;
Local Variables: These can be defined inside method, constructor or
also inside block. The scope or life time of local variable destroyed
with end of method completion.
2. Data Type
Byte
Short
Int
Long
Char
Float
Double
Boolean
Page | 2
Mobile Application Development – Prepared By: Asst. Prof. Jenis Shah
Mobile Application Development
3. String
String s1= “Welcome to Android Lecture Series”;
String s2 = new String(“This is example of String”);
Functions : compare(), concat(), equals(), split(), length(), replace(),
compareTo(), charAt(), endsWith(), indexOf(), trim(),
toLowerCase(),startsWith()
4. Operators
4.1 Arithmetic Operator : +, -, /, *, %
4.2 Unary Operator : +2, -2, x++, --x,
4.3 Equality & Relational Opeator : = =, !=, <, >, <=, >=
4.4 Conditional Operator : &&, ||, ?:
4.5 Assignment : =, +=, -=, *=,
4.6 Bitwise Operator : &, ^, |,
class LearnAndroid{
int sub_code;
String file_path;
7. Arrays
Array Declaration in JAVA
int[] arr;
Page | 3
Mobile Application Development – Prepared By: Asst. Prof. Jenis Shah
Mobile Application Development
Multidimensional Array :
Int [][] learnArray = new int[2][3];
8. Inheritance
class Base
{
//Code of Base class
}
{
//extends the properties of base class
}
9. Abstraction
It is a process of hiding internal working and showing only necessary
details.
Page | 4
Mobile Application Development – Prepared By: Asst. Prof. Jenis Shah
Mobile Application Development
psvm(String args[])
{
TestAndroid ta = new TestAndroid();
ta.test();
}
10. Interface
- 100% Abstraction
- Contains methods which has no implementation
- Uses implement keyword
interface vehicle {
void inition();
void breaking();
}
Page | 5
Mobile Application Development – Prepared By: Asst. Prof. Jenis Shah
Mobile Application Development
}
}
11. Encapsulation
Encapsulation is a process of hiding the data from the users or in
other words we can say it protects the code by preventing access
from the outside class.
class Test
{
int a;
int b;
12. Polymorphism
- Run time polymorphism: Dynamic Binding at Run time : Method
Overriding
- Compile time polymorphism : Method Overloading
Page | 6
Mobile Application Development – Prepared By: Asst. Prof. Jenis Shah
Mobile Application Development
class Test
{
Runtime
class Base {
public void read()
{
System.out.println(“Hello Base Class”);
}
}
class Child{
public void read()
{
System.out.println(“Hello Child Class”);
}
Page | 7
Mobile Application Development – Prepared By: Asst. Prof. Jenis Shah
Mobile Application Development
class TestRunTimePolymorphism
{
public static void main (String args[])
{
Base b = new Child();
b.read(); // call child class
Base c = new Base();
b.read(); // call base class
}
13. Constructor :
- A constructor always has a same name as the class whose instance
members they initialize.
- A constructor does not have a return type,
- not even void.
- It is because the constructor is automatically called by the compile
whenever an object of the class is created.
class Test
{
int a,b;
Test()
{
a = 3; b = 5;
}
Test(int c, int d)
{
a = c; b = d;
}
Page | 8
Mobile Application Development – Prepared By: Asst. Prof. Jenis Shah
Mobile Application Development
}
Default Constructor : public Test() {}
Parameterized Constructor: `` public Test(int c, int d) {}
Copy Constructor : Test( Test obj ) { a = obj.a; b = obj.b }
Creating Thread
- By Extending Thread Class
- Implementing Runnable Interface
Ex:
- Thread()
- Thread ( String Name)
- Thread( Runnable r)
- Thread ( Runnable r, String Name)
Methods of Thread :
Page | 9
Mobile Application Development – Prepared By: Asst. Prof. Jenis Shah
Mobile Application Development
Page | 10
Mobile Application Development – Prepared By: Asst. Prof. Jenis Shah
Mobile Application Development
}
}
Multithreading in Android
Multi-Threading in Android is a unique feature through which more than
one threads execute together without hindering the execution of other
threads.
Multi-Threading in Android is not different from conventional multi-
Threading.
Page | 11
Mobile Application Development – Prepared By: Asst. Prof. Jenis Shah
Mobile Application Development
16. Collections
Lists
- ArrayLists : ArrayList is a dynamic data structure in which you can
add or remove any number of elements and those elements are
stored in ordered sequence. It may also contain duplicate values.
aList.add(5);
aList.add(11);
aList.add(17);
- Vector:
Vector is type of data structure that implements List Interface. It is
very much similar to ArrayList as it also maintains insertion order,
that is elements are retrieved in same order as they are added into
it.
vectorObject.add(3);
vectorObject.add(5);
Page | 12
Mobile Application Development – Prepared By: Asst. Prof. Jenis Shah
Mobile Application Development
Map
- HashMaps
HashMap is a type of Collection, that stores our data in a pair such
that each element has a key associated with it. The pair of key and
value is often known as Entry and these entries can have only
unique keys.
HashMap does not allow Entry with duplicate key, it overlaps old
value with new one. Below program helps you understand this.
HashMap<Integer,String> HashMap=new
HashMap<Integer,String>();
HashMap.put(1001,"India");
- LikedHashMap,
In Addition to all the functionalities of HashMap Class, the
functionality of maintaining the insertion is added into
LinkedHashMap and to attain this functionality all the entries(key
and value) are linked to each other using doubly-linked list. This
doubly-linked list maintains the iteration ordering, which is in
general the order in which keys were added in the map.
Page | 13
Mobile Application Development – Prepared By: Asst. Prof. Jenis Shah
Mobile Application Development
SDLC
Flowchart
Improved Communication. Flowchart software empowers entire teams to
collaborate as they create, edit, and analyze flowcharts. ...
Benefit 2: Visual Clarity. ...
Benefit 3: Effective Analysis. ...
Benefit 4: Problem Solving. ...
Benefit 5: Documentation.
Page | 14
Mobile Application Development – Prepared By: Asst. Prof. Jenis Shah
Mobile Application Development
Page | 15
Mobile Application Development – Prepared By: Asst. Prof. Jenis Shah
Mobile Application Development
Page | 16
Mobile Application Development – Prepared By: Asst. Prof. Jenis Shah
Mobile Application Development
Process – Circle :
Perform some transformation of input data to get output data
Data Flow
Ex:
Context Time :
Page | 17
Mobile Application Development – Prepared By: Asst. Prof. Jenis Shah
Mobile Application Development
SQL
SQL is to insert data into specific tables and to extract that data when
required using a range of different filters.
Page | 18
Mobile Application Development – Prepared By: Asst. Prof. Jenis Shah
Mobile Application Development
Insert
Delete
Update
Read
Introduction To Android
- Open Source Linux based Operating System
- Developed by Open Handset Alliance led by Google
- Anyone can download the source code of android, change it as per
their requirements, add their own features
- Java language is mainly used to write the android code even though
other languages can be used.
- Goal of android project is to create a successful real-world product
that improves the mobile experience for end users.
Why Android ?
- Open Source
- Largest development community
- Increased marketing
- Inter app integration
- Reduced cost of development
- Higher success ratio
- Rich development environment
The Android platform provides a framework API that applications can use
to interact with the underlying Android system. The framework API
consists of:
Page | 20
Mobile Application Development – Prepared By: Asst. Prof. Jenis Shah
Mobile Application Development
Page | 21
Mobile Application Development – Prepared By: Asst. Prof. Jenis Shah
Mobile Application Development
Features Of Android
1. NTC ( Near Field Communication ) : Easily interact across short
distance
2. Alternate Keyboards
3. Infrared Transmission ( Use phone or tablet as remote control)
4. No-Touch Control ( We can say it as gesture control )
5. Automation : Control app permission like location, music etc.
6. Storage: SQLite for storage purpose in smartphones
7. Media Support : Audio, Images & Video in various formats
8. Messaging : SMS & MMS
9. Web Browser
10. Connectivity: networks like: GSM/EDGE, IDEN, CDMA, EV-DO,
UMTS, Bluetooth, WiFi, LTE and WiMAX.
11. Hardware Support : Accelerometer Sensor, Camera, Digital
Compass, Proximity Sensor & GPS and a lot more.
12. Tethering : Supports sharing of Internet as wired or wireless
hotspots.
13. Multi Touch and Multi Tasking
14. Video calling
15. Screen capture
16. External storage
17. Streaming media support
18. Optimized graphics
19. Widgets
20. Custom ROMs
Page | 22
Mobile Application Development – Prepared By: Asst. Prof. Jenis Shah
Mobile Application Development
Page | 23
Mobile Application Development – Prepared By: Asst. Prof. Jenis Shah
Mobile Application Development
Page | 24
Mobile Application Development – Prepared By: Asst. Prof. Jenis Shah
Mobile Application Development
- Android Studio
- JDK
- Genymotion ( Emulator For Developers)
Android Architecture
Linux Kernel
Android was created on the open source kernel of Linux. One main reason
for choosing this kernel was that it provided proven core features on which
to develop the Android operating system
Page | 25
Mobile Application Development – Prepared By: Asst. Prof. Jenis Shah
Mobile Application Development
HAL
Libraries:
Running on the top of the kernel, the Android framework was developed
with various features. It consists of various C/C++ core libraries with
numerous of open source tools. Some of these are:
On the top of linux kernel, their are Native libraries such as WebKit,
OpenGL, FreeType, SQLite, Media, C runtime library (libc) etc.
The WebKit library is responsible for browser support, SQLite is for
database, FreeType for font support, Media for playing and recording audio
and video formats.
• android.app − Provides access to the application model and is the
cornerstone of all Android applications.
• android.content − Facilitates content access, publishing and messaging
between applications and application components.
• android.database − Used to access data published by content providers and
includes SQLite database management classes.
• android.opengl − A Java interface to the OpenGL ES 3D graphics rendering
API.
• android.os − Provides applications with access to standard operating system
services including messages, system services and inter-process
communication.
• android.text − Used to render and manipulate text on a device display.
• android.view − The fundamental building blocks of application user
interfaces.
• android.widget − A rich collection of pre-built user interface components
such as buttons, labels, list views, layout managers, radio buttons etc.
• android.webkit − A set of classes intended to allow web-browsing
capabilities to be built into applications.
Page | 26
Mobile Application Development – Prepared By: Asst. Prof. Jenis Shah
Mobile Application Development
WebKit:
This open source web browser engine provides all the functionality to
display web content and to simplify page loading.
Media frameworks:
These libraries allow you to play and record audio and video.
The Dalvik VM uses the device’s underlying Linux kernel to handle low-
level functionality ,including security, threading and memory management.
It consumes less memory and provides fast performance.
Application Framework
Page | 27
Mobile Application Development – Prepared By: Asst. Prof. Jenis Shah
Mobile Application Development
The Android team has built on a known set proven libraries, built in the
background, and all of it these is exposed through Android interfaces.
These interfaces warp up all the various libraries and make them useful for
the Developer.
1. Activity Manager:
It manages the activity lifecycle and the activity stack.
2. Telephony Manager:
It provides access to telephony services as related subscriber
information, such as phone numbers.
3. View System:
It builds the user interface by handling the views and layouts.
4. Location manager:
It finds the device’s geographic location.
5. Content Providers − Allows applications to publish and share data
with other applications.
6. Resource Manager − Provides access to non-code embedded
resources such as strings, color settings and user interface layouts.
7. Notifications Manager − Allows applications to display alerts and
notifications to the user.
Applications:
Android applications can be found at the topmost layer. At application
layer we write our application to be installed on this layer only. Examples
of applications are Games, Messages, Contacts etc.
Page | 28
Mobile Application Development – Prepared By: Asst. Prof. Jenis Shah
Mobile Application Development
Page | 29
Mobile Application Development – Prepared By: Asst. Prof. Jenis Shah
Mobile Application Development
Page | 30
Mobile Application Development – Prepared By: Asst. Prof. Jenis Shah
Mobile Application Development
Page | 31
Mobile Application Development – Prepared By: Asst. Prof. Jenis Shah
Mobile Application Development
Page | 32
Mobile Application Development – Prepared By: Asst. Prof. Jenis Shah
Mobile Application Development
Firebase
Google Map
Google Places
Google Cloud Messaging Services
Graphics Programming
Page | 33
Mobile Application Development – Prepared By: Asst. Prof. Jenis Shah
Mobile Application Development
Hindi – Telugu
English as a co
- Need Common Language As well as Same Grammar rules and
medium to communicate
Android “ java code ==== MySQL Server has .net
1. Common language: XML or JSON ( Transfer the data bet technologies
)
2. Grammar rules : Protocols
3. Medium : Local Network or Internet
Page | 34
Mobile Application Development – Prepared By: Asst. Prof. Jenis Shah
Mobile Application Development
Activity Stage
Page | 35
Mobile Application Development – Prepared By: Asst. Prof. Jenis Shah
Mobile Application Development
Page | 36
Mobile Application Development – Prepared By: Asst. Prof. Jenis Shah
Mobile Application Development
Main Activity.java
package com.example.activitylifecycledemojjs;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toast toast;
Toast.makeText(getApplicationContext(), "onCreate Called",
Toast.LENGTH_LONG).show();
Page | 37
Mobile Application Development – Prepared By: Asst. Prof. Jenis Shah
Mobile Application Development
@Override
protected void onRestart() {
super.onRestart();
Toast toast;
Toast.makeText(getApplicationContext(), "onRestart Called",
Toast.LENGTH_LONG).show();
}
SecondActivity.java
package com.example.activitylifecycledemojjs;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Gravity;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;
import com.example.activitylifecycledemojjs.R.layout;
Page | 38
Mobile Application Development – Prepared By: Asst. Prof. Jenis Shah
Mobile Application Development
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(layout.activity_second);
Toast toast;
toast = Toast.makeText(this, "Second On Crreate",
Toast.LENGTH_LONG);
toast.setGravity(Gravity.CENTER, 0, 0);
toast.show();
@Override
protected void onRestart() {
super.onRestart();
Toast toast;
toast = Toast.makeText(this, "Second On Restart",
Toast.LENGTH_LONG);
toast.setGravity(Gravity.CENTER, 0, 0);
toast.show();
Page | 39
Mobile Application Development – Prepared By: Asst. Prof. Jenis Shah
Mobile Application Development
Activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.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"
android:background="@color/teal_200"
tools:context=".MainActivity">
<TextView
android:id="@+id/firstActivity"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:fontFamily="serif-monospace"
android:text="First Activity"
android:textSize="36sp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.499" />
</androidx.constraintlayout.widget.ConstraintLayout>
Page | 40
Mobile Application Development – Prepared By: Asst. Prof. Jenis Shah
Mobile Application Development
Activity_second.xml
<EditText
android:id="@+id/firstActivity"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:fontFamily="serif-monospace"
android:text="Second Activity"
android:textSize="36sp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
String.xml
<resources>
<string name="app_name">ActivityLifeCycleDemoJJS-2</string>
</resources>
Colors.xml
Page | 41
Mobile Application Development – Prepared By: Asst. Prof. Jenis Shah
Mobile Application Development
Page | 42
Mobile Application Development – Prepared By: Asst. Prof. Jenis Shah
Mobile Application Development
Fragments
History
Introduction
Page | 43
Mobile Application Development – Prepared By: Asst. Prof. Jenis Shah
Mobile Application Development
Page | 44
Mobile Application Development – Prepared By: Asst. Prof. Jenis Shah
Mobile Application Development
Ex 2 for Concept:
Page | 45
Mobile Application Development – Prepared By: Asst. Prof. Jenis Shah
Mobile Application Development
Fragment Lifecycle
Page | 46
Mobile Application Development – Prepared By: Asst. Prof. Jenis Shah
Mobile Application Development
<fragment
android:id="@+id/frg1"
android:layout_width="match_parent"
android:layout_height="match_parent"
Page | 47
Mobile Application Development – Prepared By: Asst. Prof. Jenis Shah
Mobile Application Development
android:layout_weight="1"
android:name="com.example.fragmentexample.Frg1"/>
</LinearLayout>
Steps
1. Create another layout xml file for fragment
2. Create fragment ( By Extending the fragment class )
3. Set the layout xml file to fragment
4. Use fragment tag to include fragment in xml layout
</LinearLayout>
2. Sample.java
package com.example.simplefragmentdemo;
import android.os.Bundle;
import androidx.fragment.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup
container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_sample, container,
false);
}
}
Page | 48
Mobile Application Development – Prepared By: Asst. Prof. Jenis Shah
Mobile Application Development
3. AcivityMain.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity"
android:background="@color/activity_color">
<fragment
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/sampleFragment"
android:name="com.example.simplefragmentdemo.sample"
android:layout_margin="15dp"/>
</LinearLayout>
4. MainActivity.java
package com.example.simplefragmentdemo;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
Page | 49
Mobile Application Development – Prepared By: Asst. Prof. Jenis Shah
Mobile Application Development
android:layout_height="match_parent"
tools:context=".MainActivity"
android:orientation="horizontal">
<fragment
android:id="@+id/frg1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1"
android:name="com.example.fragmentexample.Frg1"/>
<fragment
android:id="@+id/frg2"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1"
android:name="com.example.fragmentexample.Frg2"/>
<fragment
android:id="@+id/frg3"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1"
android:name="com.example.fragmentexample.Frg3"/>
</LinearLayout>
2. Fragment_Frg1.xml
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".Frg1">
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#FFC6C6"
android:text="Learn" />
</FrameLayout>
3. Fragment_frg2.xml
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".Frg2">
Page | 50
Mobile Application Development – Prepared By: Asst. Prof. Jenis Shah
Mobile Application Development
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#AAC6C6"
android:text="With" />
</FrameLayout>
4. Fragment_frg3.xml
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".Frg3">
5. Mainactivity.java
package com.example.fragmentexample;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
Button actbtn;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
actbtn = (Button) findViewById(R.id.actbtn);
actbtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(getApplicationContext(),"On Click In
Activity",Toast.LENGTH_LONG).show();
}
});
}
6. Frg1.java
Page | 51
Mobile Application Development – Prepared By: Asst. Prof. Jenis Shah
Mobile Application Development
package com.example.fragmentexample;
import android.os.Bundle;
import androidx.fragment.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup
container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_frg1, container,
false);
}
}
7. Frg2.java
package com.example.fragmentexample;
import android.os.Bundle;
import androidx.fragment.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup
container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_frg2, container,
false);
}
}
8. Frg3.java
package com.example.fragmentexample;
import android.os.Bundle;
import androidx.fragment.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class Frg3 extends Fragment {
Page | 52
Mobile Application Development – Prepared By: Asst. Prof. Jenis Shah
Mobile Application Development
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup
container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_frg3, container,
false);
}
}
Add Fragments
1. Create another layout xml file for fragment
2. Create fragment ( By Extending the fragment class )
3. Set the layout xml file to fragment
4. Host a layout that will host a Fragment
5. Writing a code to add fragment to Activity in Activity.xml File
1. Fragment_Sample2.xml
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".SampleFragment2"
android:background="@color/teal_200"
>
</FrameLayout>
2. SampleFragment2.java
package com.example.fragmentdemoexm;
import android.os.Bundle;
import androidx.fragment.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class SampleFragment2 extends Fragment {
Page | 53
Mobile Application Development – Prepared By: Asst. Prof. Jenis Shah
Mobile Application Development
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup
container, Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_sample2,
container, false);
}
}
3. ActivityMain.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity"
android:background="@color/purple_200">
<FrameLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/fragmentContainer1"
android:layout_margin="5dp"/>
</LinearLayout>
4. MainActivity.java
package com.example.fragmentdemoexm;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;
import android.os.Bundle;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
addFragment();
}
}
}
ADD – Fragment Method Steps
Page | 54
Mobile Application Development – Prepared By: Asst. Prof. Jenis Shah
Mobile Application Development
Logs in Android
API for sending log output.
Generally, you should use the Log.v(), Log.d(), Log.i(), Log.w(), and Log.e()
methods to write logs. You can then view the logs in logcat.
Page | 55
Mobile Application Development – Prepared By: Asst. Prof. Jenis Shah
Mobile Application Development
Page | 56
Mobile Application Development – Prepared By: Asst. Prof. Jenis Shah
Mobile Application Development
</FrameLayout>
2. SampleFragment1.java
package com.example.activityfragmentlifecyclerelation;
import android.content.Context;
import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
Page | 57
Mobile Application Development – Prepared By: Asst. Prof. Jenis Shah
Mobile Application Development
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.i(TAG,"ON Create Called");
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup
container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
Log.i(TAG,"ON CreateView Called");
return inflater.inflate(R.layout.fragment_sample1, container,
false);
}
@Override
public void onStart() {
super.onStart();
Log.i(TAG,"ON Start Called");
}
@Override
public void onPause() {
super.onPause();
Log.i(TAG,"ON Pause Called");
}
@Override
public void onResume() {
super.onResume();
Log.i(TAG,"ON Resume Called");
}
@Override
public void onDetach() {
super.onDetach();
Log.i(TAG,"ON Detach Called");
}
@Override
public void onDestroyView() {
super.onDestroyView();
Log.i(TAG,"ON DestroyView Called");
}
@Override
public void onAttach(Context context) {
super.onAttach(context);
Log.i(TAG,"ON Attach Called");
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
Log.i(TAG,"ON ActivityCreated Called");
}
@Override
public void onStop() {
super.onStop();
Page | 58
Mobile Application Development – Prepared By: Asst. Prof. Jenis Shah
Mobile Application Development
@Override
public void onDestroy() {
super.onDestroy();
Log.i(TAG,"ON Destroy Called");
}
3. Activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity"
android:background="@color/purple_700">
<FrameLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="15dp"
android:id="@+id/frg1"/>
</LinearLayout>
4. MainActivity.java
package com.example.activityfragmentlifecyclerelation;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;
import android.os.Bundle;
import android.util.Log;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.i(TAG,"ON Create Called");
addFragment();
}
Page | 59
Mobile Application Development – Prepared By: Asst. Prof. Jenis Shah
Mobile Application Development
FragmentTransaction fragmentTransaction =
fragmentManager.beginTransaction();
SampleFragment1 sampleFragment1 = new SampleFragment1();
fragmentTransaction.add(R.id.frg1,sampleFragment1);
fragmentTransaction.commit();
}
@Override
protected void onStart() {
super.onStart();
Log.i(TAG,"ON Start Called");
}
@Override
protected void onResume() {
super.onResume();
Log.i(TAG,"ON Resume Called");
}
@Override
protected void onPause() {
super.onPause();
Log.i(TAG,"ON Pause Called");
}
@Override
protected void onStop() {
super.onStop();
Log.i(TAG,"ON Stop Called");
}
@Override
protected void onRestart() {
super.onRestart();
Log.i(TAG,"ON Restart Called");
}
@Override
protected void onDestroy() {
super.onDestroy();
Log.i(TAG,"ON Destroy Called");
}
}
O/P:
Page | 60
Mobile Application Development – Prepared By: Asst. Prof. Jenis Shah
Mobile Application Development
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/buttonAddFrg"
android:text="Add Fragment"/>
<FrameLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="15dp"
android:id="@+id/frg1"/>
</LinearLayout>
Page | 61
Mobile Application Development – Prepared By: Asst. Prof. Jenis Shah
Mobile Application Development
O/P
Page | 62
Mobile Application Development – Prepared By: Asst. Prof. Jenis Shah
Mobile Application Development
BackStack in Fragments
With this : when click on Back button – first fragment will remove then by
clicking on Back button again – then and only then Activity will remove
Motto : We will create 3 – fragments then add them into backstack and try to
check how backstack works.
1. Fragment_Sample1.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".SampleFragment1"
android:orientation="vertical"
android:gravity="center"
android:background="@color/frg1_color">
</LinearLayout>
2. Fragment_Sample2.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
Page | 63
Mobile Application Development – Prepared By: Asst. Prof. Jenis Shah
Mobile Application Development
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".SampleFragment2"
android:orientation="vertical"
android:gravity="center"
android:background="@color/frg2_color">
</LinearLayout>
3. Fragment_Sample3.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".SampleFragment3"
android:orientation="vertical"
android:gravity="center"
android:background="@color/frg3_color">
</LinearLayout>
4. SampleFragment1.java
package com.example.fragmentwithbackstack;
import android.os.Bundle;
import androidx.fragment.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
Page | 64
Mobile Application Development – Prepared By: Asst. Prof. Jenis Shah
Mobile Application Development
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup
container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_sample1, container,
false);
}
}
5. SampleFragment2.java
package com.example.fragmentwithbackstack;
import android.os.Bundle;
import androidx.fragment.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup
container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_sample2, container,
false);
}
}
6. SampleFragment3.java
package com.example.fragmentwithbackstack;
import android.os.Bundle;
import androidx.fragment.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup
container,
Page | 65
Mobile Application Development – Prepared By: Asst. Prof. Jenis Shah
Mobile Application Development
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_sample3, container,
false);
}
}
7. Activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity"
android:background="@color/teal_700"
android:orientation="vertical">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="20sp"
android:id="@+id/textCount"
android:text="Count is = "/>
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/buttonAddFrg"
android:text="Add Fragment"/>
<FrameLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="15dp"
android:id="@+id/fragment_container"/>
</LinearLayout>
8. Mainactivity.java
package com.example.fragmentwithbackstack;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
Page | 66
Mobile Application Development – Prepared By: Asst. Prof. Jenis Shah
Mobile Application Development
@Override
protected void onStart() {
super.onStart();
Log.i(TAG,"ON Start Called");
}
@Override
protected void onResume() {
super.onResume();
Log.i(TAG,"ON Resume Called");
}
@Override
protected void onPause() {
super.onPause();
Log.i(TAG,"ON Pause Called");
}
@Override
protected void onStop() {
super.onStop();
Log.i(TAG,"ON Stop Called");
}
@Override
protected void onRestart() {
super.onRestart();
Log.i(TAG,"ON Restart Called");
}
@Override
protected void onDestroy() {
super.onDestroy();
Page | 67
Mobile Application Development – Prepared By: Asst. Prof. Jenis Shah
Mobile Application Development
Page | 68
Mobile Application Development – Prepared By: Asst. Prof. Jenis Shah
Mobile Application Development
REMOVE FRAGMENT
1. In above code – Comment the addToBackstack() line
// fragmentTransaction.addToBackStack(null); & Run the code…
So now : When you press back button from any fragment : App will
directly get closed and No Back Stack Count will be maintained as no
fragment will be added in back stack
2. Add A Method : onBackPressed() // TO Remove Fragment
@Override
public void onBackPressed(){
Fragment fragment =
fragmentManager.findFragmentById(R.id.fragment_container);
if(fragment!=null)
{
fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.remove(fragment);
fragmentTransaction.commit();
}
else {
super.onBackPressed();
}
}
Now run the program and check the output by clicking on the add fragment
and then back button…
As you can click on the Add Fragment Button : Only Fragment 1 will be added
one above another
So, to get Fragment 1 – 2 – 3 – By clicking on add button we need to edit code
of the previous addFragment Method()
Page | 69
Mobile Application Development – Prepared By: Asst. Prof. Jenis Shah
Mobile Application Development
// fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
}
fragment = fragmentManager.findFragmentById(R.id.fragment_container);
if(fragment instanceof SampleFragment1){
fragment = new SampleFragment2();
}
else if(fragment instanceof SampleFragment2)
{
fragment = new SampleFragment3();
}
else if(fragment instanceof SampleFragment3)
{
fragment = new SampleFragment1();
}
else{
fragment = new SampleFragment1();
}
fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.add(R.id.fragment_container,fragment);
fragmentTransaction.commit();
}
asdasdasā
Page | 70
Mobile Application Development – Prepared By: Asst. Prof. Jenis Shah
Mobile Application Development
fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.fragment_container,fragment);
fragmentTransaction.commit();
}
Page | 71
Mobile Application Development – Prepared By: Asst. Prof. Jenis Shah
Mobile Application Development
Intents in Android
Page | 72
Mobile Application Development – Prepared By: Asst. Prof. Jenis Shah
Mobile Application Development
Structure of Intent
Two important things are there in intent :
1. Action: The general action to be performed, such as ACTION_VIEW,
ACTION_EDIT, ACTION_MAIN, etc.
2. Data: The data to operate on, such as a person record in the contacts
database, expressed as a Uri
Examples:
- ACTION_VIEW content://contacts/people/1 -- Display
information about the person whose identifier is "1".
- ACTION_DIAL content://contacts/people/1 -- Display the phone
dialer with the person filled in.
- ACTION_VIEW tel:123 -- Display the phone dialer with the given
number filled in
- ACTION_DIAL tel:123 -- Display the phone dialer with the given
number filled in.
- ACTION_EDIT content://contacts/people/1 -- Edit information
about the person whose identifier is "1".
- ACTION_VIEW content://contacts/people/ -- Display a list of
people, which the user can browse through.
-
With this The Secondary Attributes are as below:
- Category -- Gives additional information about the action to
execute. Ex: CATEGORY_LAUNCHER : appear in launcher
- Type: - Specifies an explicit type (a MIME type) of the intent data.
Page | 73
Mobile Application Development – Prepared By: Asst. Prof. Jenis Shah
Mobile Application Development
2. Explicit intents:
- specify which application will satisfy the intent, by supplying either
the target app's package name or a fully-qualified component class
name
- In Explicit we use the name of component which will be affected by
Intent.
- Explicit Intent work internally within an application to perform
navigation and data transfer.
(How you can navigate from one activity to another activity)
Page | 74
Mobile Application Development – Prepared By: Asst. Prof. Jenis Shah
Mobile Application Development
<EditText
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:id="@+id/editTextData"
android:layout_marginTop="100dp"
android:layout_marginLeft="20dp"
android:ems="10"
/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/implicit_button"
android:text="Click Here"
android:layout_marginTop="120dp"
android:layout_marginLeft="50dp"
/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/explicit_button"
android:text="Click To Go Second"
android:layout_marginTop="130dp"
android:layout_marginLeft="50dp"
/>
</LinearLayout>
Page | 75
Mobile Application Development – Prepared By: Asst. Prof. Jenis Shah
Mobile Application Development
2. Activiy_second.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".SecondActivity"
android:background="@color/purple_200">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="This is Second Activity"
android:id="@+id/second_text_view"
android:layout_marginTop="130dp"
android:layout_marginLeft="50dp"
/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/second_button"
android:text="Click To Go First"
android:layout_marginTop="130dp"
android:layout_marginLeft="20dp"
/>
</LinearLayout>
3. MainActivity.java
package com.example.implicitexplicitintent;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
Page | 76
Mobile Application Development – Prepared By: Asst. Prof. Jenis Shah
Mobile Application Development
startActivity(intent);
}
});
// code for explicit intent
explicitButton.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View v) {
Intent intent = new Intent(getApplicationContext(),
SecondActivity.class);
startActivity(intent);
}
});
}
}
4. SecondActivity.java
package com.example.implicitexplicitintent;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
secondBtn = findViewById(R.id.second_button);
secondBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(getApplicationContext(),
MainActivity.class);
startActivity(intent);
}
});
}
}
Page | 77
Mobile Application Development – Prepared By: Asst. Prof. Jenis Shah
Mobile Application Development
Page | 78
Mobile Application Development – Prepared By: Asst. Prof. Jenis Shah
Mobile Application Development
2 nd Example of Intents
MainActivity.java
package com.example.implicitexplicitintent;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
}
}
Activity_Main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
Page | 79
Mobile Application Development – Prepared By: Asst. Prof. Jenis Shah
Mobile Application Development
<EditText
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:id="@+id/editTextData"
android:layout_marginTop="100dp"
android:layout_marginLeft="20dp"
android:ems="10"
/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/implicit_button"
android:text="Click Here"
android:layout_marginTop="120dp"
android:layout_marginLeft="50dp"
/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/explicit_button"
android:text="Click To Go Second"
android:layout_marginTop="130dp"
android:layout_marginLeft="50dp"
/>
</LinearLayout>
Second Activity.java
package com.example.implicitexplicitintent;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
secondBtn = findViewById(R.id.second_button);
secondBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(getApplicationContext(),
MainActivity.class);
startActivity(intent);
}
});
Page | 80
Mobile Application Development – Prepared By: Asst. Prof. Jenis Shah
Mobile Application Development
}
}
Activity_Second.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".SecondActivity"
android:background="@color/purple_200">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="This is Second Activity"
android:id="@+id/second_text_view"
android:layout_marginTop="130dp"
android:layout_marginLeft="50dp"
/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/second_button"
android:text="Click To Go First"
android:layout_marginTop="130dp"
android:layout_marginLeft="20dp"
/>
</LinearLayout>
O/P
Page | 81
Mobile Application Development – Prepared By: Asst. Prof. Jenis Shah
Mobile Application Development
LAYOUTS IN ANDROID
• A layout defines the structure for a user interface in your app, such as in
an activity.
• Android Layout is used to define the user interface that holds the UI
controls or widgets that will appear on the screen of an android
application or activity screen.
• 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
structure for View and other ViewGroup
View
• A View is a simple building block of a user interface.
• It is a small rectangular box that can be TextView, EditText, or even a
button.
• Usage : It occupies the area on the screen in a rectangular area and is
responsible for drawing and event handling.
• The use of a view is to draw content on the screen of the user’s Android
device.
• All of the views in a window are arranged in a single tree.
• Implementation : You can add views either from code or by specifying a
tree of views in one or more XML layout files.
Types of Views
1. TextView
2. EditText
3. Button
4. Image Button
5. Date Picker
6. RadioButton
7. CheckBox buttons
8. Image View
Page | 82
Mobile Application Development – Prepared By: Asst. Prof. Jenis Shah
Mobile Application Development
View Group
• A View Group is a subclass of the ViewClass and can be considered as a
superclass of Layouts.
• It provides an invisible container to hold the views or layouts.
• ViewGroup instances and views work together as a container for
Layouts
• The subclasses of the ViewGroup:
1. LinearLayout
2. RelativeLayout
3. FrameLayout
4. GridView
5. ListView
Note: The View objects are usually called "widgets" and can be one of many
subclasses, such as Button or TextView.
The ViewGroup objects are usually called "layouts" can be one of many types
that provide a different layout structure, such as LinearLayout or
ConstraintLayout .
Page | 83
Mobile Application Development – Prepared By: Asst. Prof. Jenis Shah
Mobile Application Development
Layout Declaration
• 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.
- You can also use Android Studio's Layout Editor to build your
XML layout using a drag-and-drop interface.
• Instantiate Layout Element at Runtime
- Your app can create View and ViewGroup objects (and manipulate
their properties) programmatically.
Types of Layouts
• Linear Layout
• Relative Layout
• Constraint Layout
• Table Layout
• Frame Layout
• List View
• Grid View
• Absolute Layout
• WebView
• ScrollView
Page | 84
Mobile Application Development – Prepared By: Asst. Prof. Jenis Shah
Mobile Application Development
Ex of Code
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<TextView android:id="@+id/text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="I am a TextView" />
<Button android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="I am a Button" />
</LinearLayout>
Page | 85
Mobile Application Development – Prepared By: Asst. Prof. Jenis Shah
Mobile Application Development
1. LinearLayout:
a. Vertical
In this all the child are arranged vertically in a line one after the other.
b. Horizontal
In this all the child are arranged horizontally in a line one after the
other.
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Button 1"
android:id="@+id/btn1"
android:backgroundTint="#358a32" />
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Button 2"
android:id="@+id/btn2"
android:backgroundTint="#FFBA32" />
<Button
Page | 86
Mobile Application Development – Prepared By: Asst. Prof. Jenis Shah
Mobile Application Development
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Button 3"
android:id="@+id/btn3"
android:backgroundTint="#0472f2" />
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Button 4"
android:id="@+id/btn4"
android:backgroundTint="#e100d5" />
</LinearLayout>
O/P
Page | 87
Mobile Application Development – Prepared By: Asst. Prof. Jenis Shah
Mobile Application Development
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button 2"
android:id="@+id/btn2"
android:backgroundTint="#FFBA32" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button 3"
android:id="@+id/btn3"
android:backgroundTint="#0472f2" />
</LinearLayout>
O/P
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical"> <!-- Vertical Orientation set -->
<!-- Put Child Views like Button here -->
</LinearLayout>
Page | 88
Mobile Application Development – Prepared By: Asst. Prof. Jenis Shah
Mobile Application Development
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"> <!-- Horizontal Orientation set -->
<!-- Child Views are here -->
</LinearLayout>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button 2"
android:id="@+id/btn2"
android:backgroundTint="#FFBA32" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button 3"
android:id="@+id/btn3"
android:backgroundTint="#0472f2" />
</LinearLayout>
Page | 89
Mobile Application Development – Prepared By: Asst. Prof. Jenis Shah
Mobile Application Development
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button 1"
android:id="@+id/btn1"
android:backgroundTint="#358a32"
android:layout_weight="2"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button 2"
android:id="@+id/btn2"
android:backgroundTint="#FFBA32"
android:layout_weight="1"/>
</LinearLayout>
Page | 90
Mobile Application Development – Prepared By: Asst. Prof. Jenis Shah
Mobile Application Development
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Button 1"
android:id="@+id/btn1"
android:backgroundTint="#358a32"
android:layout_weight="2"/>
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Button 2"
android:id="@+id/btn2"
android:backgroundTint="#FFBA32"
android:layout_weight="1"/>
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Button 3"
Page | 91
Mobile Application Development – Prepared By: Asst. Prof. Jenis Shah
Mobile Application Development
android:id="@+id/btn3"
android:layout_weight="1"
android:backgroundTint="#0472f2" />
</LinearLayout>
Page | 92
Mobile Application Development – Prepared By: Asst. Prof. Jenis Shah
Mobile Application Development
Attribute Description
layout_alignParentTop If it specified “true”, the top edge of view will match the top edge of the
parent.
layout_alignParentBottom If it specified “true”, the bottom edge of view will match the bottom edge
of parent.
layout_alignParentLeft If it specified “true”, the left edge of view will match the left edge of parent.
layout_alignParentRight If it specified “true”, the right edge of view will match the right edge of the
parent.
layout_centerInParent If it specified “true”, the view will be aligned to the centre of parent.
layout_centerHorizontal If it specified “true”, the view will be horizontally centre aligned within its
parent.
layout_centerVertical If it specified “true”, the view will be vertically centre aligned within its
parent.
layout_above It accepts another sibling view id and places the view above the specified
view id.
layout_below It accepts another sibling view id and places the view below the specified
view id.
layout_toLeftOf It accepts another sibling view id and places the view left of the specified
Page | 93
Mobile Application Development – Prepared By: Asst. Prof. Jenis Shah
Mobile Application Development
view id.
layout_toRightOf It accepts another sibling view id and places the view right of the specified
view id.
layout_toStartOf It accepts another sibling view id and places the view to start of the
specified view id.
layout_toEndOf It accepts another sibling view id and places the view to the end of the
specified view id.
Example:
Relative_Layout_Example.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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=".RelativeLayoutExample"
android:paddingLeft="10dp"
android:paddingRight="10dp">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button 1"
android:id="@+id/btn1"
android:backgroundTint="#358a32"
android:layout_alignParentLeft="true"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button 2"
android:id="@+id/btn2"
android:backgroundTint="#358a32"
android:layout_alignParentRight="true"
android:layout_centerVertical="true"/>
<Button
android:id="@+id/btn3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_centerVertical="true"
android:text="Button3" />
<Button
Page | 94
Mobile Application Development – Prepared By: Asst. Prof. Jenis Shah
Mobile Application Development
android:id="@+id/btn4"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:text="Button4" />
<Button
android:id="@+id/btn5"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="@+id/btn2"
android:layout_centerHorizontal="true"
android:text="Button5" />
<Button
android:id="@+id/btn6"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="@+id/btn4"
android:layout_centerHorizontal="true"
android:text="Button6" />
<Button
android:id="@+id/btn7"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toEndOf="@+id/btn1"
android:layout_toRightOf="@+id/btn1"
android:layout_alignParentRight="true"
android:text="Button7" />
</RelativeLayout>
(There is no change in default java file of this layout file)
Page | 95
Mobile Application Development – Prepared By: Asst. Prof. Jenis Shah
Mobile Application Development
Constrain Layout
• Similar to Relative Layout
• Constraint Layout is a ViewGroup (i.e. a view that holds other views)
which allows you to create large and complex layouts with a flat view
hierarchy.
• It allows you to position and size widgets in a very flexible way.
• It was created to help reduce the nesting of views and also improve the
performance of layout files.
• All the power of ConstraintLayout is available directly from the Layout
Editor's visual tools.
• So you can build your layout with ConstraintLayout entirely by drag-
and-dropping instead of editing the XML.
• To define a view's position in ConstraintLayout, you must add at least
one horizontal and one vertical constraint for the view.
• Each constraint represents a connection or alignment to another view,
the parent layout, or an invisible guideline.
• Each constraint defines the view's position along either the vertical or
horizontal axis.
• When you drop a view into the Layout Editor, it stays where you leave it
even if it has no constraints. if a view has no constraints when you run
your layout on a device, it is drawn at position [0,0] (the top-left
corner).
Page | 96
Mobile Application Development – Prepared By: Asst. Prof. Jenis Shah
Mobile Application Development
Delete a constrain
Page | 97
Mobile Application Development – Prepared By: Asst. Prof. Jenis Shah
Mobile Application Development
• Using horizontal axis, you can set positioning of one widget in right, left,
end and start sides of other widget.
• While using vertical axis you can set bottom, top sides and text baseline.
Page | 98
Mobile Application Development – Prepared By: Asst. Prof. Jenis Shah
Mobile Application Development
Use Guidelines
Table Layout
• In Android, Table Layout is used to arrange the group of views into rows
and columns.
• Table Layout containers do not display a border line for their columns,
rows or cells.
• Table will have as many columns as the row with the most cells.
• A table can also leave the cells empty but cells can’t span the columns as
they can in HTML
Page | 99
Mobile Application Development – Prepared By: Asst. Prof. Jenis Shah
Mobile Application Development
Imp Points
• For building a row in a table we will use the <TableRow> element.
Table row objects are the child views of a table layout.
• Each row of the table has zero or more cells and each cell can hold only
one view object like ImageView, TextView or any other view.
• Total width of a table is defined by its parent container
• Column can be both stretchable and shrinkable.
• If shrinkable then the width of column can be shrunk to fit the table into
its parent object and
• if stretchable then it can expand in width to fit any extra space available.
• We cannot specify the width of the children’s of the Table layout.
• Here, width always match parent width.
• The height attribute can be defined by a child; default value of height
attribute is wrap content.
Basic Code
<TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:collapseColumns="0"> <!-- collapse the first column of the table row--
>
<!-- first row of the table layout-->
<TableRow
android:id="@+id/row1"
android:layout_width="match_parent"
android:layout_height="wrap_content">
</TableRow>
</TableLayout>
Page | 100
Mobile Application Development – Prepared By: Asst. Prof. Jenis Shah
Mobile Application Development
Page | 101
Mobile Application Development – Prepared By: Asst. Prof. Jenis Shah
Mobile Application Development
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Hyderabad" />
</TableRow>
</TableLayout>
1
android:id
This is the ID which uniquely identifies the layout.
2
android:collapseColumns
This specifies the zero-based index of the columns to collapse. The
Page | 102
Mobile Application Development – Prepared By: Asst. Prof. Jenis Shah
Mobile Application Development
3
android:shrinkColumns
The zero-based index of the columns to shrink. The column indices must
be separated by a comma: 1, 2, 5.
4
android:stretchColumns
The zero-based index of the columns to stretch. The column indices must
be separated by a comma: 1, 2, 5
<TableRow
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<TextView
android:text="Time"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_column="1" />
<TextClock
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/textClock"
android:layout_column="2" />
</TableRow>
<TableRow>
<TextView
android:text="First Name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_column="1" />
<EditText
android:width="200px"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
Page | 103
Mobile Application Development – Prepared By: Asst. Prof. Jenis Shah
Mobile Application Development
</TableRow>
<TableRow>
<TextView
android:text="Last Name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_column="1" />
<EditText
android:width="100px"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</TableRow>
<TableRow
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<RatingBar
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/ratingBar"
android:layout_column="2" />
</TableRow>
<TableRow
android:layout_width="fill_parent"
android:layout_height="fill_parent"/>
<TableRow
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Submit"
android:id="@+id/button"
android:layout_column="2" />
</TableRow>
</TableLayout>
Page | 104
Mobile Application Development – Prepared By: Asst. Prof. Jenis Shah
Mobile Application Development
ShrinkColumn Example
<TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:shrinkColumns="0"> <!-- shrink the first column of the layout-->
Page | 105
Mobile Application Development – Prepared By: Asst. Prof. Jenis Shah
Mobile Application Development
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#b0b0b0"
android:padding="18dip"
android:text="Shrink Column Example"
android:textColor="#000"
android:textSize="18dp" />
</TableRow>
</TableLayout>
<!-- first element of the row that is the part of table but it is
invisible-->
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#b0b0b0"
android:padding="18dip"
android:text="Columns 1"
android:textColor="#000"
Page | 106
Mobile Application Development – Prepared By: Asst. Prof. Jenis Shah
Mobile Application Development
android:textSize="18dp" />
<TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#000"
android:orientation="vertical"
android:stretchColumns="1">
<TableRow android:padding="5dip">
<TextView
android:layout_height="wrap_content"
android:layout_marginBottom="20dp"
android:layout_span="2"
android:gravity="center_horizontal"
android:text="@string/loginForm"
android:textColor="#0ff"
android:textSize="25sp"
android:textStyle="bold" />
</TableRow>
Page | 107
Mobile Application Development – Prepared By: Asst. Prof. Jenis Shah
Mobile Application Development
<TableRow>
<TextView
android:layout_height="wrap_content"
android:layout_column="0"
android:layout_marginLeft="10dp"
android:text="@string/userName"
android:textColor="#fff"
android:textSize="16sp" />
<EditText
android:id="@+id/userName"
android:layout_height="wrap_content"
android:layout_column="1"
android:layout_marginLeft="10dp"
android:background="#fff"
android:hint="@string/userName"
android:padding="5dp"
android:textColor="#000" />
</TableRow>
<TableRow>
<TextView
android:layout_height="wrap_content"
android:layout_column="0"
android:layout_marginLeft="10dp"
android:layout_marginTop="20dp"
android:text="@string/password"
android:textColor="#fff"
android:textSize="16sp" />
<EditText
android:id="@+id/password"
android:layout_height="wrap_content"
android:layout_column="1"
Page | 108
Mobile Application Development – Prepared By: Asst. Prof. Jenis Shah
Mobile Application Development
android:layout_marginLeft="10dp"
android:layout_marginTop="20dp"
android:background="#fff"
android:hint="@string/password"
android:padding="5dp"
android:textColor="#000" />
</TableRow>
<TableRow android:layout_marginTop="20dp">
<Button
android:id="@+id/loginBtn"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_span="2"
android:background="#0ff"
android:text="@string/login"
android:textColor="#000"
android:textSize="20sp"
android:textStyle="bold" />
</TableRow>
</TableLayout>
Main Activity.java
package example.abhiandriod.tablelayoutexample;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
Page | 109
Mobile Application Development – Prepared By: Asst. Prof. Jenis Shah
Mobile Application Development
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// initiate a button
Button loginButton = (Button) findViewById(R.id.loginBtn);
// perform click event on the button
loginButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(getApplicationContext(), "Hello AbhiAndroid..!!!",
Toast.LENGTH_LONG).show(); // display a toast message
}
});
}
String.xml
<resources>
<string name="app_name">TableLayoutExample</string>
<string name="hello_world">Hello world!</string>
<string name="action_settings">Settings</string>
<string name="loginForm">Login Form</string>
<string name="userName">UserName</string>
<string name="password">Password</string>
<string name="login">LogIn</string>
</resources>
Page | 110
Mobile Application Development – Prepared By: Asst. Prof. Jenis Shah
Mobile Application Development
Frame Layout
Attributes
1. android:foreground
Foreground defines the drawable to draw over the content and this may
be a color value.
Possible color values can be in the form of “#rgb”, “#argb”, “#rrggbb”, or
“#aarrggbb”. This all are different color code model used
2. android:foregroundGravity
Page | 111
Mobile Application Development – Prepared By: Asst. Prof. Jenis Shah
Mobile Application Development
3. android:visibility
4. android:measureAllChildren
This determines whether to measure all children including gone state
visibility or just those which are in the visible or invisible state of
measuring visibility. The default value of measureallchildren is false. We
can set values in the form of Boolean i.e. “true” OR “false”.
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_height="match_parent"
android:layout_width="match_parent"
>
<TextView android:text="LeftTop"
android:layout_width="wrap_content"
Page | 112
Mobile Application Development – Prepared By: Asst. Prof. Jenis Shah
Mobile Application Development
android:layout_height="wrap_content" />
<TextView android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:text="RightTop"
android:layout_gravity="top|right" />
<TextView android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:text="CentreTop"
android:layout_gravity="top|center_horizontal" />
<TextView android:text="Left"
android:layout_gravity="left|center_vertical"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<TextView android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:text="Right"
android:layout_gravity="right|center_vertical" />
<TextView android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:text="Centre"
android:layout_gravity="center" />
<TextView android:text="LeftBottom"
android:layout_gravity="left|bottom"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<TextView android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:text="RightBottom"
android:layout_gravity="right|bottom" />
<TextView android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:text="CenterBottom"
android:layout_gravity="center|bottom" />
</FrameLayout>
Page | 113
Mobile Application Development – Prepared By: Asst. Prof. Jenis Shah
Mobile Application Development
Foreground
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/framelayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="center"
android:foregroundGravity="fill"
android:foreground="#0f0"><!--foreground color for a FrameLayout-->
<LinearLayout
android:orientation="vertical"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
>
<!-- Imageview will not be shown because of foreground color which is drawn over
it-->
<ImageView
android:layout_width="200dp"
android:layout_height="200dp"
android:layout_marginBottom="10dp"
android:src="@mipmap/ic_launcher"
android:scaleType="centerCrop"
/>
<!--Textview will not be shown because of foreground color is drawn over it-->
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center_horizontal"
android:text="abhiAndroid"/>
Page | 114
Mobile Application Development – Prepared By: Asst. Prof. Jenis Shah
Mobile Application Development
</LinearLayout>
</FrameLayout>
</FrameLayout>
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.demo);
FrameLayout frame=(FrameLayout)findViewById(R.id.frame);
frame.measure(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED);
int width = frame.getMeasuredWidth();
int height = frame.getMeasuredHeight();
Toast.makeText(getApplicationContext(),"width="+width+"
height="+height,Toast.LENGTH_SHORT).show();
Page | 115
Mobile Application Development – Prepared By: Asst. Prof. Jenis Shah
Mobile Application Development
Example 3 :
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/frameLayout"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<ImageView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:scaleType="fitXY"
android:src="@drawable/img_name" /><!--Change image as per your name of
image saved in drawable-->
<TextView
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:gravity="center"
android:text="abhiAndroid"
android:textSize="30sp"
android:textColor="#f3f3f3"
android:textStyle="bold" />
</FrameLayout>
Jaba
package abhiandroid.com.farmelayoutjava;
import android.graphics.Color;
Page | 116
Mobile Application Development – Prepared By: Asst. Prof. Jenis Shah
Mobile Application Development
import android.graphics.Typeface;
import android.os.Bundle;
import android.app.Activity;
import android.view.Gravity;
import android.view.Menu;
import android.widget.AbsListView;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
Page | 117
Mobile Application Development – Prepared By: Asst. Prof. Jenis Shah
Mobile Application Development
framelayout.addView(imageView);
framelayout.addView(textView1);
setContentView(framelayout);
}
ADAPTER
Page | 118
Mobile Application Development – Prepared By: Asst. Prof. Jenis Shah
Mobile Application Development
Adapters in Android
1. Base Adapter
- BaseAdapter is a common base class of a general implementation
of an Adapter that can be used in ListView, GridView, Spinner etc.
- Whenever we need a customized list in a ListView or customized
grids in a GridView we create our own adapter and extend base
adapter in that.
- Base Adapter can be extended to create a custom Adapter for
displaying a custom list item.
- ArrayAdapter is also an implementation of BaseAdapter.
@Override
public int getCount() {
return 0;
}
@Override
public Object getItem(int i) {
return null;
}
Page | 119
Mobile Application Development – Prepared By: Asst. Prof. Jenis Shah
Mobile Application Development
@Override
public long getItemId(int i) {
return 0;
}
@Override
public View getView(int i, View view, ViewGroup viewGroup) {
return null;
}
we see the overrided functions of BaseAdapter which are used to set the data
in a list, grid or a spinner.
2. Array Adapter
- Whenever we have a list of single items which is backed by an
Array, we can use ArrayAdapter.
- For instance, list of phone contacts, countries or names.
- ArrayAdapter(Context context, int resource, int textViewResourceId,
T[] objects)
Page | 120
Mobile Application Development – Prepared By: Asst. Prof. Jenis Shah
Mobile Application Development
}
@Override
public int getCount() {
return super.getCount();
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
return super.getView(position, convertView, parent);
}
}
Page | 121
Mobile Application Development – Prepared By: Asst. Prof. Jenis Shah
Mobile Application Development
@Override
public View getView(int position, View convertView, ViewGroup parent) {
return super.getView(position, convertView, parent);
@Override
public int getCount() {
return super.getCount();
}
}
List View :
• List of scrollable items can be displayed in Android using ListView.
• It helps you to displaying the data in the form of a scrollable list.
• Users can then select any list item by clicking on it.
• ListView is default scrollable so we do not need to use scroll View or
anything else with ListView.
Page | 122
Mobile Application Development – Prepared By: Asst. Prof. Jenis Shah
Mobile Application Development
<ListView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/simpleListView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
tools:context="abhiandroid.com.listexample.MainActivity">
</ListView>
Attributes:
- Id : id is used to uniquely identify a ListView.
- divider: This is a drawable or color to draw between different list
items.
- dividerHeight: This specify the height of the divider between list
items. This could be in dp(density pixel),sp(scale independent
pixel) or px(pixel).
- listSelector: listSelector property is used to set the selector of the
listView. It is generally orange or Sky blue color mostly but you
can also define your custom color or an image as a list selector as
per your design.
- <!-- List Selector Code in ListView -->
- <ListView
- android:id="@+id/simpleListView"
- android:layout_width="fill_parent"
- android:layout_height="wrap_content"
- android:divider="#f00"
- android:dividerHeight="1dp"
- android:listSelector="#0f0"/> <!--list selector in green color-->
Page | 123
Mobile Application Development – Prepared By: Asst. Prof. Jenis Shah
Mobile Application Development
1.Array Adapter:
Whenever you have a list of single items which is backed by an array, you can
use ArrayAdapter. For instance, list of phone contacts, countries or names.
Note : By default, ArrayAdapter expects a Layout with a single TextView, If
you want to use more complex views means more customization in list items,
please avoid ArrayAdapter and use custom adapters.
Example:
MainActivity.xml
<ListView
android:id="@+id/simpleListView"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
Page | 124
Mobile Application Development – Prepared By: Asst. Prof. Jenis Shah
Mobile Application Development
android:divider="@color/material_blue_grey_800"
android:dividerHeight="1dp" />
</LinearLayout>
LIstView.xml
<TextView
android:id="@+id/textView"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:padding="@dimen/activity_horizontal_margin"
android:textColor="@color/black" />
</LinearLayout>
Main Activity.Java
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.widget.ArrayAdapter;import android.widget.ListView;
Page | 125
Mobile Application Development – Prepared By: Asst. Prof. Jenis Shah
Mobile Application Development
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
simpleList = (ListView)findViewById(R.id.simpleListView);
ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(this,
R.layout.activity_listview, R.id.textView, countryList);
simpleList.setAdapter(arrayAdapter);
}
}
Example 2 :
ActivityMain.xml
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<ListView
android:id="@+id/list"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</LinearLayout>
Activiymain.Java
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
ListView l;
Page | 126
Mobile Application Development – Prepared By: Asst. Prof. Jenis Shah
Mobile Application Development
String tutorials[]
= { "Algorithms", "Data Structures",
"Languages", "Interview Corner",
"GATE", "ISRO CS",
"UGC NET CS", "CS Subjects",
"Web Technologies" };
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
l = findViewById(R.id.list);
ArrayAdapter<String> arr;
arr
= new ArrayAdapter<String>(
this,
R.layout.support_simple_spinner_dropdown_item,
tutorials);
l.setAdapter(arr);
}
}
Main Activity.xml
<ListView
android:id="@+id/simpleListView"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:divider="@color/material_blue_grey_800"
android:dividerHeight="1dp"
android:footerDividersEnabled="false" />
</LinearLayout>
Page | 127
Mobile Application Development – Prepared By: Asst. Prof. Jenis Shah
Mobile Application Development
Activity_listview.xml
<ImageView
android:id="@+id/icon"
android:layout_width="50dp"
android:layout_height="50dp"
android:src="@drawable/ic_launcher" />
<TextView
android:id="@+id/textView"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:padding="@dimen/activity_horizontal_margin"
android:textColor="@color/black" />
</LinearLayout>
Main Activity.Java
import android.app.Activity;
import android.os.Bundle;
import android.widget.ListView;
ListView simpleList;
String countryList[] = {"India", "China", "australia", "Portugle", "America",
"NewZealand"};
int flags[] = {R.drawable.india, R.drawable.china, R.drawable.australia,
R.drawable.portugle, R.drawable.america, R.drawable.new_zealand};
Page | 128
Mobile Application Development – Prepared By: Asst. Prof. Jenis Shah
Mobile Application Development
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
simpleList = (ListView) findViewById(R.id.simpleListView);
CustomAdapter customAdapter = new CustomAdapter(getApplicationContext(),
countryList, flags);
simpleList.setAdapter(customAdapter);
}
}
CustomAdapter.java
import android.content.Context;
import android.media.Image;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import java.util.zip.Inflater;
Page | 129
Mobile Application Development – Prepared By: Asst. Prof. Jenis Shah
Mobile Application Development
@Override
public int getCount() {
return countryList.length;
}
@Override
public Object getItem(int i) {
return null;
}
@Override
public long getItemId(int i) {
return 0;
}
@Override
public View getView(int i, View view, ViewGroup viewGroup) {
view = inflter.inflate(R.layout.activity_listview, null);
TextView country = (TextView) view.findViewById(R.id.textView);
ImageView icon = (ImageView) view.findViewById(R.id.icon);
country.setText(countryList[i]);
icon.setImageResource(flags[i]);
return view;
}
Page | 130
Mobile Application Development – Prepared By: Asst. Prof. Jenis Shah
Mobile Application Development
<item>Australia</item>
<item>England</item>
<item>New Zealand</item>
<item>Sri Lanka</item>
<item>Pakistan</item>
<item>West Indies</item>
<item>Bangladesh</item>
<item>Ireland</item>
</string-array>
</resources>
2. List_View.xml
package journaldev.com.listview;
import android.app.ListActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
Page | 131
Mobile Application Development – Prepared By: Asst. Prof. Jenis Shah
Mobile Application Development
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// storing string resources into Array
String[] teams = getResources().getStringArray(R.array.teams);
ListView lv = getListView();
// selected item
String team = ((TextView) view).getText().toString();
}
});
}
}
Page | 132
Mobile Application Development – Prepared By: Asst. Prof. Jenis Shah
Mobile Application Development
4. SecondActivity.java
package journaldev.com.listview;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.widget.TextView;
Intent i = getIntent();
// getting attached intent data
String product = i.getStringExtra("team");
// displaying selected product name
txtProduct.setText(product);
}
}
Page | 133
Mobile Application Development – Prepared By: Asst. Prof. Jenis Shah
Mobile Application Development
<ListView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/listView2"
android:divider="#ff4432"
android:dividerHeight="2dp"/>
</LinearLayout>
Acitivity_list_view.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".ListView">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/listTextView"
android:layout_gravity="center"
android:padding="5dp"
android:textColor="@color/black"/>
</LinearLayout>
Listview.java
package com.example.finallistviewex2;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
@Override
protected void onCreate(Bundle savedInstanceState) {
Page | 134
Mobile Application Development – Prepared By: Asst. Prof. Jenis Shah
Mobile Application Development
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list_view);
}
}
Main Activity.java
package com.example.finallistviewex2;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.ArrayAdapter;
ListView lv;
String data [] = {"AI", "MAD", "ML", "MCWC", "CD"};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
lv = findViewById(R.id.listView2);
ArrayAdapter<String> arrayAdapter = new
ArrayAdapter<String>(this,R.layout.activity_list_view,R.id.listTextView,dat
a);
lv.setAdapter(arrayAdapter);
}
}
Example2
Activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity"
android:padding="15dp"
android:orientation="vertical">
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
Page | 135
Mobile Application Development – Prepared By: Asst. Prof. Jenis Shah
Mobile Application Development
android:text="SampleList"
android:textSize="20sp"
android:textColor="@color/black"
/>
<ListView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/listInstitutes"
android:divider="#AAf002"
android:dividerHeight="1dp"
android:listSelector="#FFA200"/>
</LinearLayout>
String.xml
<resources>
<string name="app_name">FinalListViewEx</string>
<string-array name="LJU">
<item>LJIET</item>
<item>LJMCA</item>
<item>LJ Diploma</item>
<item>LJ Pharma</item>
<item>LJ Arch</item>
</string-array>
</resources>
MainActivity.Java
package com.example.finallistviewex;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
ListView lvInstitutes;
String [] institutes;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
lvInstitutes = findViewById(R.id.listInstitutes);
institutes = getResources().getStringArray(R.array.LJU);
ArrayAdapter<String> instituteAdapter = new
ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,institutes);
lvInstitutes.setAdapter(instituteAdapter);
}
}
Page | 136
Mobile Application Development – Prepared By: Asst. Prof. Jenis Shah
Mobile Application Development
TAB LAYOUT
Page | 137
Mobile Application Development – Prepared By: Asst. Prof. Jenis Shah
Mobile Application Development
Below we firstly create a new tab and then add it in the TabLayout and
set the true value for setSelected parameter that makes it selectable.
Page | 138
Mobile Application Development – Prepared By: Asst. Prof. Jenis Shah
Mobile Application Development
4. addTab(Tab tab, int position): This method is used to add a tab in the
TabLayout and set the state for the tab. By using this method we add the
tab which we created using newTab() method in the TabLayout. The tab
will be inserted at the given position. If it is the first tab to be added
then it will become the selected tab.
Below we firstly create a new tab and then add it in the TabLayout at a
specific position.
Page | 139
Mobile Application Development – Prepared By: Asst. Prof. Jenis Shah
Mobile Application Development
7. getTabAt(int index): This method is used to get the tab at the specified
index. This method returns TabLayout.Tab.
Below we get the total number of tabs currently registered with the
action bar.
TabLayout tabLayout = (TabLayout) findViewById(R.id.simpleTabLayout); // get the
reference of TabLayout
int tabCount= tabLayout.getTabCount(); // get the total number of tabs currently
registered with the action bar.
10. getTabGravity(): This method is used to get the current gravity used
for laying out tabs. This method returns the gravity which we set using
setTabGravity(int gravity) method.
Below we firstly set the gravity and then get the current gravity used for
laying out tabs.
11. setTabMode(int mode): This method is used to set the behavior mode
for the Tabs in this layout. The valid input options are:
MODE_FIXED: Fixed tabs display all tabs concurrently and are best used
with content that benefits from quick pivots between tabs.
Page | 141
Mobile Application Development – Prepared By: Asst. Prof. Jenis Shah
Mobile Application Development
Below we set the tab text colors for the both states of the tab.
14. getTabTextColors(): This method is used to get the text colors for the
different states (normal, selected) of the tabs. This method returns the
text color which we set using setTabTextColors(int normalColor, int
selectedColor) method.
Below we firstly set the text colors and then get the text colors for the
both states of the tab.
15. removeAllTabs(): This method is used to remove all tabs from the
action bar and deselect the current tab.
Below we remove all the tabs from the action bar and deselect the
current tab.
Page | 142
Mobile Application Development – Prepared By: Asst. Prof. Jenis Shah
Mobile Application Development
tabLayout.removeAllTabs(); // remove all the tabs from the action bar and deselect
the current tab
@Override
public void onTabUnselected(TabLayout.Tab tab) {
// called when tab unselected
}
@Override
public void onTabReselected(TabLayout.Tab tab) {
// called when a tab is reselected
}
});
17. removeTab(Tab tab): This method is used to remove a tab from the
layout. In this method we pass the TabLayout.Tab object to remove the
tab from the layout. If the removed tab was selected then it will be
automatically deselected and another tab will be selected if present in
the TabLayout.
Below we firstly create and add a tab and then remove it from the
TabLayout.
Page | 143
Mobile Application Development – Prepared By: Asst. Prof. Jenis Shah
Mobile Application Development
Below we set the red color for the selected tab indicator.
ViewPager in Android
• Layout manager that allows the user to flip left and right through pages
of data. You supply an implementation of a PagerAdapter to generate
the pages that the view shows.
• There are standard adapters implemented for using fragments with the
ViewPager, which cover the most common use cases.
Page | 145
Mobile Application Development – Prepared By: Asst. Prof. Jenis Shah
Mobile Application Development
3. It works even better when the content of the fragments are static than
something that constantly changes or gets updated.
Page | 146
Mobile Application Development – Prepared By: Asst. Prof. Jenis Shah
Mobile Application Development
<com.google.android.material.tabs.TabLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/tab_layout"
/>
<androidx.viewpager2.widget.ViewPager2
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/view_pager2"
/>
</LinearLayout>
</FrameLayout>
Fragment-2.xml
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".SeconfFragment">
Page | 147
Mobile Application Development – Prepared By: Asst. Prof. Jenis Shah
Mobile Application Development
</FrameLayout>
Fragment-3.xml
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".ThirdFragment">
</FrameLayout>
FirstFragment.java
package com.example.fragmentex3;
import android.os.Bundle;
import androidx.fragment.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_first, container, false);
Page | 148
Mobile Application Development – Prepared By: Asst. Prof. Jenis Shah
Mobile Application Development
}
}
SecondFragment.java
package com.example.fragmentex3;
import android.os.Bundle;
import androidx.fragment.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_seconf, container,
false);
}
}
ThirdFragment.java
package com.example.fragmentex3;
import android.os.Bundle;
import androidx.fragment.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_third, container, false);
}
}
Page | 149
Mobile Application Development – Prepared By: Asst. Prof. Jenis Shah
Mobile Application Development
package com.example.fragmentex3;
import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.lifecycle.Lifecycle;
import androidx.viewpager2.adapter.FragmentStateAdapter;
@Override
public Fragment createFragment(int position) {
switch (position)
{
case 1: return new SeconfFragment();// if position is one then
call second fragment
case 2: return new ThirdFragment(); // if position is two then
call third fragment
}
return new FirstFragment(); // default cases it will call first
fragment object and bind to the viewpager / layout
}
@Override
public int getItemCount() {
return 3; // as we have only 3 Fragments to view so we can set it
to 3 as static value
}
}
MainActivity.Java Code
package com.example.fragmentex3;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.FragmentManager;
import androidx.viewpager2.widget.ViewPager2;
import android.os.Bundle;
import com.google.android.material.tabs.TabLayout;
Page | 150
Mobile Application Development – Prepared By: Asst. Prof. Jenis Shah
Mobile Application Development
TabLayout tabLayout;
ViewPager2 viewPager2;
FragmentAdapter fragmentAdapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tabLayout = findViewById(R.id.tab_layout);
viewPager2 = findViewById(R.id.view_pager2);
FragmentManager fm = getSupportFragmentManager();
fragmentAdapter = new FragmentAdapter(fm, getLifecycle());
viewPager2.setAdapter(fragmentAdapter);
tabLayout.addTab(tabLayout.newTab().setText("First"));
tabLayout.addTab(tabLayout.newTab().setText("Second"));
tabLayout.addTab(tabLayout.newTab().setText("Third"));
tabLayout.addOnTabSelectedListener(new
TabLayout.OnTabSelectedListener() {
@Override
public void onTabSelected(TabLayout.Tab tab) {
viewPager2.setCurrentItem(tab.getPosition());
}
@Override
public void onTabUnselected(TabLayout.Tab tab) {
@Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
viewPager2.registerOnPageChangeCallback(new
ViewPager2.OnPageChangeCallback() {
@Override
public void onPageSelected(int position) {
tabLayout.selectTab(tabLayout.getTabAt(position));
}
});
}
}
Page | 151
Mobile Application Development – Prepared By: Asst. Prof. Jenis Shah
Mobile Application Development
o/p
Page | 152
Mobile Application Development – Prepared By: Asst. Prof. Jenis Shah