0% found this document useful (0 votes)
2 views

Chapter AT2

Chapter 2 covers Android layout and UI widgets, explaining the concepts of Views and ViewGroups, including various layout types such as LinearLayout and RelativeLayout. It details the attributes and measurements for layouts, as well as common UI widgets like Button, TextView, and EditText, along with event handling mechanisms. The chapter also discusses the Activity lifecycle and the use of Fragments for better UI management on different screen sizes.

Uploaded by

tilay1921
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

Chapter AT2

Chapter 2 covers Android layout and UI widgets, explaining the concepts of Views and ViewGroups, including various layout types such as LinearLayout and RelativeLayout. It details the attributes and measurements for layouts, as well as common UI widgets like Button, TextView, and EditText, along with event handling mechanisms. The chapter also discusses the Activity lifecycle and the use of Fragments for better UI management on different screen sizes.

Uploaded by

tilay1921
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 43

Chapter 2

Android Layout and UI widgets


Views and View Groups
View:
anything which occupies a rectangular area on the
screen
is responsible for drawing and event handling
every UI (Button, EditText, CheckBox etc) element is
subclass of view (android.view.View)
ViewGroup:
is a subclass of View (android.view.View)
provides invisible container that hold other views or
other ViewGroups and define their layout properties
It is the base class for layouts and views
containers.
 It contains commonly used subclasses like
RelativeLayout, LinearLayout, ListView, GridView
etc
Layouts and its types
Layouts are subclasses of ViewGroup
which specifies how a view should be
arranged inside the viewgroups
The standard Layouts are:
LinearLayout: arranges its children in a
single column or a single row.
RelativeLayout: the positions of the
children can be described in relation to each
other or to the parent.
FrameLayout: It is used to block out an
area on the screen to display a single item.
TableLayout: arranges its children into rows
and columns.
Linear Layout
 is a view group that aligns all children in a single
direction, vertically or horizontally
 Layout direction is specified:
android:orientation=”horizontal”
android:orientation=”vertically”
 Example:
<LinearLayout . . .
android:orientation="horizontal">

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World" />

</LinearLayout>
RelativeLayout
 lays out elements based on their relationships with one
another, and with the parent container.
 These properties will layout elements relative to the
parent:
 android:layout_alignParentBottom-places the element on
the bottom of the container.
 android:layout_alignParentLeft-places the element on the
left side of the container.
 android:layout_alignParentRight-places the element on the
right side of the container.
 android:layout_alignParentTop-places the element on the
top of the container.
 android:layout_centerHorizontal-centers the elements
horizontally within its parent container.
 android:layout_centerInParent- centers the elements both
horizontally and vertically within its parent container.
 android:layout_centerVertical- centers the elements
vertically within its parent container.
Relative to other element: Given the element’s Id:
“@id/xxxxx”
 android:layout_above- places an element above the specified
element.
 android:layout_below- places an element below the specified
element.
 android:layout_toLeftOf- places an element to the left of the
specified element.
 android:layout_toRightOf- places an element to the right of
the specified element.
 android:layout_alignBaseline- aligns baseline of the new
element with baseline of the specified element.
 android:layout_alignBottom- aligns bottom of the new
element in with bottom of the specified element.
 android:layout_alignLeft- aligns left edge of the new element
with left edge of the specified element.
 android:layout_alignRight- aligns right edge of the new
element with right edge of the specified element.
 android:layout_alignTop- places top of the new element in
alignment with the top of the specified element.
Example
<RelativeLayout …>

<TextView

android:id="@+id/textview"
android:layout_alignParentTop="true"
android:layout_centerInParent="true"/>
<Button

android:id="@+id/button1"
android:layout_below="@+id/textview"
android:layout_alignParentStart="true"/>

</RelativeLayout>
Layout Attributes
 Each layout has a set of attributes that define its visual
properties.
 Some of the common attributes are:
android:id - uniquely identifies the view.
android:layout_width or layout_height – defines
width and height of the layout
android:layout_marginTop , Bottom,Lefft, Right-
defines extra space arroung the layout.
android:layout_gravity- specifies how child Views are
positioned.
android:layout_weight- specifies how much of the
extra space in the layout should be allocated to the
View.
android:layout_x or y - This specifies the x or y -
coordinate of the layout.
android:paddingLeft, Right, Top, Bottom - defines
the padding filled for the layout.
Width and Height Measurements
 dp (Density-independent Pixels),
 sp ( Scale-independent Pixels),
 pt ( Points which is 1/72 of an inch),
 px ( Pixels),
 mm ( Millimeters) and finally in (inches)
 In most cases width and height of a layout are
specified in
android:layout_width=wrap_content - tells your view
to size itself to the dimensions required by its content.
android:layout_width=fill_parent - tells your view to
become as big as its parent view.
 Gravity plays a great role in positioning the view
object. The values of android:layout_gravity property
are:
Top, bottom, right, left, center, start, end, center_vertical,
center_horizontal, fill_vertical, fill_horizontal etc
Android UI widgets
 input controls which are used to build a user interface
(views)
 It includes Button, TextView, EditView, ImageView,
CheckBox, RadioButton, ProgressBar, Spinner,
TimePicker etc.
Button
 A GUI component that is sensible to taps (clicks) by the
user
 represented by the Android class
android.widget.button
 It can be created in two types:
Button with Text
Button with Images
 Button instance can be inserted into GUI either through
.xml file or
programmatically in .java file.
 In xml file
<Button
android:id="@+id/btn1 "
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Display"
/>
 Programmatically in java file
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button button=new Button(this);//creating instance
button.setText("Display");//setting a text
RelativeLayout relativeLayout=(RelativeLayout)
findViewById(R.id.rootlayout); // creating a viewGroup layout and find a
layout
relativeLayout.addView(button);//add button to the layout
}}
Adding a click event to the button
Use android:onClick attribute to specify the
event type in the xml file for the button and set
the method as its value
Example: android:onClick=”btnOnclick()”
Go to the java button and define the method.
Example:
protected void btnClick(View view)
{
Toast.makeText(getBaseContext(), “Button
Clicked!”,Toast.LENGTH_SHORT).show();
}
The above method will be invoked when the user
clicks on the button and will display “Button
Clicked!” message upon click
Toast
 Is a notification message that pop up for a specific
duration
 Uses android.widget.Toast class which is the subclass
of java.lang.Object class
 Example:
Toast toast=Toast.makeText(getApplicationContext(), “Button
Clicked!”,Toast.LENGTH_SHORT);
toast.setGravity(Gravity.AXIS_PULL_AFTER,0,0);
toast.show();
 The method takes three parameters:
an application context, the text message and the
duration(Toast.LENGTH_SHORT-display the message for
2second and Toast.LENGHT_LONG- for 3.5 seconds) for the
toast.
 setGravity() is used for positioning the toast. The
standard toast appears at bottom of the screen,
centered horizontally
TextView
 is used to display text to the user (label)
 Example
<TextView
android:id="@+id/txtview "
android:layout_width="fill_parent "
android:layout_height="wrap_content"
android:text="Hello World"
/>
EditText
 allows users to edit its text content. It is also known as a text
field
 It can be either single line or multi-line.
 Touching a text field places the cursor and automatically
displays the keyboard.
 In addition to typing, text fields allow for a variety of
activities such as text selection (cut, copy, paste) and data
look-up via auto-completion.
 Example:
<EditText
android:id="@+id/search "
android:layout_width="fill_parent "
android:layout_height="wrap_content"
android:hint="Search Tex"
android:inputType="text"
android:imeOptions="actionSend“ />
 The common input types
text- displays a normal text keyboard
textEmailAddress- displays a normal text keyboard
with the @ character
textUri- displays a normal text keyboard with the /
character
number- displays a basic number keypad
phone- displays a phone style keypad
The inputType property also allows you to specify
keyboard behavior:
textCapSentences-displays normal text keyboard
that capitalizes the first letter for each new sentence.
textCapWords- displays normal text keyboard that
capitalizes every word.
textAutoCorrect- displays normal text keyboard
that corrects commonly misspelled words
textPassword- displays normal text keyboard but
the characters entered turn into dots.
textMultiLine- displays normal text keyboard that
allow users to input long strings of text that include
line breaks.(carriage return)
android:imeOptions attribute allows you to specify
an action for the EditText. Such as Search or Send.
Example: android:imeOptions=”actionSend”
Listening to keyboard action
 listen for a specific action event(for example actionSend)
using an TextView.onEditorActionListener
 TextView.onEditorActionListener interface provides a
callback method called onEditorAction() that indicates the
action type invoked with an action ID such as
IME_ACTION_SEND or IME_ACTION_SEARCH
 Example:
EditText editText= (EditText) findViewById(R.id.search);
editText.setOnEditorActionListener(new OnEditorActionListener(){
@Override
Public boolean onEditorAction(TextView v,int actionId, KeyEvent event){
boolean handled=false;
if(actionId==EditorInfo.IME_ACTION_SEND){
sendMessage();
handled=true;
}
return handled;
} });
AutoCompleteTextView
 is a view that is similar to EditText, except that it shows a
list of completion suggestions automatically while the user
is typing (in dropdown form)
 Create AutoCompleteTextView in the xml
<AutoCompleteTextView
android:layout_width="match_parent "
android:layout_height="wrap_content"
android:id="@+id/course_list"
/>
 Create the list in res/values/string.xml
<resources>
<string-array name="course_array">
<item>OOP in Java</item>
<item>Data Structures in Java</item>
<item>Advanced Progarmming using Java</item>
</string-array>
</resources>
CheckBox
Allows the user to select one or more options
from a set
Typically you should present each checkbox
option in a vertical list
ToggleButton
Allows the user to change a setting between two
states
From API 14, you may use a Switch, that
provides a slider control
<ToggleButton
android:id="@+id/toggleButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content“
android:textOff=“Off"
android:textOn=“On"
android:checked="true"/>
RadioButton
Allows the user to select one option from a set
RadioGroup ensures that only one radio button
can be selected at a time

The method onRadioButtonClicked handles the


click event
Android Event Handling
 Events are a useful way to collect data about a user's
interaction with interactive components of Applications
 Android framework maintains an event queue as first-in, first-
out (FIFO) basis
 There are three concepts related to Android Event
Management −
 Event Listeners − an interface in the View class that
contains a single callback method. These methods will be
called by the Android framework when the View to which the
listener has been registered is triggered by user interaction
with the item in the UI.
 Event Listeners Registration − is the process by which an
Event Handler gets registered with an Event Listener so that
the handler is called when the Event Listener fires the event.
 Event Handlers − When an event happens and we have
registered an event listener for the event, the event listener
calls the Event Handlers, which is the method that actually
handles the event.
handlers are:
Event Handler Event Listener & Description
OnClickListener()-called when the user either clicks or
onClick() touches or focuses upon any widget like button, text,
image etc

OnLongClickListener()-Pressing or touching UI element for one or


onLongClick()
more seconds.
onFocusChange() OnFocusChangeListener()- called when the widget looses its focus
OnFocusChangeListener()-called when the user is focused on the
onKey()
item and presses a key.
OnTouchListener() -called when the user presses the key, releases the
onTouch()
key, or any movement gesture on the screen.
OnMenuItemClickListener()- called when the user selects a menu
onMenuItemClick()
item.
onCreateContextMe onCreateContextMenuItemListener()-is called when the context
nu() menu is being built(as the result of a sustained "long click)
Activity
 represents a single screen with a user interface (UI)
and it will act as an entry point for users to interact
with an app
 Android apps can contain multiple screens and each
screen of our application is an extension of Activity
class (MainActivity class)
 Example: Contacts App
List of contacts
Add new contacts
Search contacts
 in android there is a minimal dependency between
the activities in an app.
 To uses the activities in application
we need to register those activities information in our
app’s manifest file (AndroidMainfest.xml) and
need to manage activity life cycle properly
activities can be implemented as a subclass
of Activity class
import android.app.Activity;
import android.os.Bundle;
public class MainActivity extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
}
Life Cycles of an Activity
onCreate() — Called when the activity is first created
onStart() — Called when the activity becomes visible
to the user
onResume() — Called when the activity starts
interacting with the user onCreate()
onPause() — Called when the current activity is
being paused and the previous activity is being
resumed
onStop() — Called when the activity is no longer
visible to the user
onDestroy() — Called before the activity is
destroyed by the system (either manually or by the
system to conserve memory)
onRestart() — Called when the activity has been
stopped and is restarting again
Fragments
In a small-screen device (such as a smartphone),
an activity typically fills the entire screen
but in a large-screen device, such as on a tablet,
it is somewhat out of place
all the views in an activity must be arranged to
make full use of the increased space, a
better approach is to use “mini-activities”,
each containing its own set of views.
In Android 3.0 and later, these mini-activities
are known as fragments.
Fragments are always embedded in an activity
Fragments
Life Cycle of Fragments
Method Description

onAttach() It is called when the fragment has been associated with an activity.

onCreate() It is used to initialize the fragment.

onCreateView() It is used to create a view hierarchy associated with the fragment.

onActivityCreated() It is called when the fragment activity has been created and the fragment view
hierarchy instantiated.

onStart() It is used to make the fragment visible.

onResume() It is used to make the fragment visible in an activity.

onPause() It is called when fragment is no longer visible and it indicates that the user is
leaving the fragment.

onStop() It is called to stop the fragment using onStop() method.

onDestoryView() The view hierarchy which associated with the fragment is being removed after
executing this method.

onDestroy() It is called to perform a final clean up of the fragments state.

onDetach() It is called immediately after the fragment disassociated from the activity.
Intents
Android uses Intent for communicating between
the components (such as activities, services,
broadcast receivers and content providers) of an
Application and also from one application to
another application.
It helps you to redirect your activity to another
activity on occurrence of any event
 For example startActivity() you can perform this
task.
Intent intent = new Intent(getApplicationContext(),
SecondActivity.class);
startActivity(intent);
foreground activity is getting redirected to another
activity i.e. SecondActivity.java.
getApplicationContext() returns the context for your
foreground activity
Types of Intents
 Explicit Intent:
 Explicit Intents are used to connect the application internally.
 In Explicit we use the name of component which will be affected by
Intent
 Explicit Intent works internally within an application to perform
navigation and data transfer. Example:
Intent intent = new Intent(getApplicationContext(), SecondActivity.class);
startActivity(intent);
 Here SecondActivity is the JAVA class name where the activity will now
be navigated.
Implicit Intent:
 In Implicit Intents we do need to specify the name of the component.
 We just specify the Action which has to be performed and further this
action is handled by the component of another application. The basic
example of implicit Intent is to open any web page.
Intent intentObj = new Intent(Intent.ACTION_VIEW);
intentObj.setData(Uri.parse("https://www.google.com"));
startActivity(intentObj);
 Unlike Explicit Intent you do not use any class name to pass through
Intent().
 Example
Benefits of Intents
For activity: Intent object helps to start a new
activity and passing data to the second activity
For Services: Services work in background,
Intents could be used to start a Service
For Broadcast Receivers: Android system
initiates some broadcast message on several
events, such as System Reboot, Low Battery
warning message etc.
For Android Applications: Whenever you need
to navigate to another activity of your app or you
need to send some information to next activity
then we can always prefer to Intents for doing so.
Services
 Android service is a component that is used to perform long running
operations on the background such as playing music, handle network
transactions, interacting with content providers etc.
 It doesn't have any UI (user interface)
 service can be bounded by a component to perform interactivity and
inter process communication (IPC).
Life Cycle of Android Service
1) Started Service (foreground or background)
 A service is started when component (like activity) calls
startService() method, now it runs in the background indefinitely.
 It runs in the background even if the application that started the
service is closed.
 It is stopped by stopService() method.
 The service can stop itself by calling the stopSelf() method.

2) Bound Service
 A service is bound when another component (e.g. client) calls
bindService() method.
 The client can unbind the service by calling the unbindService()
method. The service cannot be stopped until all clients unbind the
service.
Menu
 Menu is a part of user interface (UI) component which is used
to handle some common functionality around the application
 useful for displaying additional options that are not directly
visible on the main UI of an application
 Menu can be defined in separate XML file and use that file in
our activities or fragments based on our requirements.
 Define android menu
 create a new folder menu inside of our project resource directory
(res/menu/) and add a new XML file to build the menu
 Use menu, item and group(Optional) xml tags
 You can also create sub menu
<item>
<menu><item></item></menu>
</item>
 Use MenuInflater.inflate() to load the menu from an activity
and define an event handler to inform what to perform when the
menu is selected
Creating Menu
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item android:id="@+id/inbox“ android:icon="@drawable/ic_inbox"
android:title="@string/inbox" />

<item android:id="@+id/compose" android:icon="@drawable/ic_comp


ose"
android:title="@string/
compose" android:showAsAction="ifRoom" />
Creating
<item Sub menu
android:id="@+id/outbox“
android:icon="@drawable/ic_outbox"
<?xml version="1.0" encoding="utf-8"?>
android:title="@string/outbox" />
<menu …>
</menu>
<item android:id="@+id/file" android:title="@string/file" >
<!-- "file" submenu -->
<menu>
<item android:id="@+id/create_new" android:title="@string/
create_new" />

<item android:id="@+id/open" android:title="@string/open" />


</menu>
</item>
</menu>
Types of Android Menu
Options Menu
Context Menu
Popup Menu
Option Menu
useful to implement actions that have a global
impact on the app, such as Settings, Search, etc
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item android:id="@+id/inbox"
android:icon="@drawable/ic_inbox"
android:title="@string/inbox" />
<item android:id="@+id/compose"
android:icon="@drawable/ic_compose"
android:title="@string/compose"
android:showAsAction="ifRoom" />
</menu>
Loading android option menu
@Override
public void onCreateOptionsMenu(ContextMenu menu, View v,
ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu_example, menu);
}
Handling android option menu click event
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.inbox:
// do something
return true;
case R.id.compose:
// do something
return true;
default:
return super.onContextItemSelected(item);
}
}
Context Menu
a floating menu that appears when the user
performs a long click on an element
more like the menu which displayed on right
click in Windows or Linux
It does not support any item shortcuts and item
icons
<?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" >
<Button
android:id="@+id/btnShow"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Long press me"
android:layout_marginTop="200dp" android:layout_marginLeft="
100dp"/>
</LinearLayout>
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button btn = (Button) findViewById(R.id.btnShow);
registerForContextMenu(btn);
}
@Override
public void onCreateContextMenu(ContextMenu menu, View v,
ContextMenu.ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
menu.setHeaderTitle("Context Menu");
menu.add(0, v.getId(), 0, "Inbox");
menu.add(0, v.getId(), 0, "Outbox");
}
Handling ContextMenu click event

@Override
public boolean onContextItemSelected(MenuItem item) {
if (item.getTitle() == "Inbox") { // do your
coding }
else { return false; }
return true;
Popup Menu
displays a list of items in a vertical list that’s
anchored to the view that invoked the menu
It does not support any item shortcuts and item
icons
Popup menu is available with API level 11
(Android 3.0) and higher versions
<?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" >

<Button
android:id="@+id/btnShow"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Show Popup Menu"
android:layout_marginTop="200dp" android:layout_marginLeft="1
00dp"/>
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/
android" >
<item android:id="@+id/inbox_item"
android:title="Inbox" />
<item android:id="@+id/compose_item"
android:title="Compose" />
<item android:id="@+id/outbox_item"
android:title="Outbox" />
<item android:id="@+id/spam_item"
android:title="Spam" />
<item android:id="@+id/logout_item"
android:title="Logout" />
</menu>
public
class MainActivity extends AppCompatActivity implements PopupMenu.O
nMenuItemClickListener {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button btn = (Button) findViewById(R.id.btnShow);
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
PopupMenu popup = new PopupMenu(MainActivity.this, v);
popup.setOnMenuItemClickListener(MainActivity.this);
popup.inflate(R.menu.popup_menu);
popup.show();
}
});
}
@Override
public boolean onMenuItemClick(MenuItem item) {
Toast.makeText(this, "Selected Item: " +item.getTitle(),
Toast.LENGTH_SHORT).show();
switch (item.getItemId()) {
case R.id.inbox_item:
// do your code
return true;
case R.id.compose_item:
// do your code
return true;
case R.id.outbox_item:
// do your code
return true;
case R.id.spam_item:
// do your code
return true;
case R.id.logout_item:
// do your code
return true;
default:
return false;
} } }

You might also like