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

Unit 4

The document discusses various layouts and UI components in Android such as LinearLayout, RelativeLayout, TableLayout, FrameLayout, and AbsoluteLayout. It explains how to declare UI elements in XML layout files and load them from an Android activity.

Uploaded by

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

Unit 4

The document discusses various layouts and UI components in Android such as LinearLayout, RelativeLayout, TableLayout, FrameLayout, and AbsoluteLayout. It explains how to declare UI elements in XML layout files and load them from an Android activity.

Uploaded by

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

Unit- 4 Android UI and Component using Fragments

In android, Layout is used to define the user interface for an app or activity and it will hold the UI
elements that will appear to the user.

The user interface in an android app is made with a collection of View and ViewGroup objects.
Generally, the android apps will contain one or more activities and each activity is a one screen
of app. The activities will contain multiple UI components and those UI components are the
instances of View and ViewGroup subclasses.

The user interface in an android app is made with a collection of View and ViewGroup objects.
Generally, the android apps will contain one or more activities and each activity is a one screen
of the app. The activities will contain multiple UI components and those UI components are the
instances of View and ViewGroup subclasses.

Android View
The View is a base class for all UI components in android. For example, the EditText class is used to
accept the input from users in android apps, which is a subclass of View.

Following are the some of common View subclasses that will be used in android applications.

• TextView
• EditText
• Button
• CheckBox
• RadioButton
• ImageButton
• Progress Bar
• Spinner

Like these we have many View subclasses available in android.

Android ViewGroup
The ViewGroup is a subclass of View and it will act as a base class for layouts and layouts parameters.
The ViewGroup will provide an invisible container to hold other Views or ViewGroups and to define
the layout properties.
For example, Linear Layout is the ViewGroup that contains a UI controls like button, textview, etc. and
other layouts also.

Following are the commonly used ViewGroup subclasses in android applications.

• Linear Layout
• Relative Layout
• Table Layout
• Frame Layout
• Web View
• List View
• Grid View

Both View and ViewGroup subclasses together will play a key role to create a layouts in android
applications.

Working with Layout:


Layout is a way to arrange components.
1) Linear Layout
2) Relative Layout
3) Table Layout
4) Frame Layout
5) Absolute Layout

Linear Layout:
This is the widely used layout in android programming.
Linear Layout arrange components in horizontal or vertical direction using android:orientation
property see the below design and code.
To create a layout use <LinerLayout> element of XML see the below example.

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"

android:layout_width="fill_parent"

android:layout_height="fill_parent"

android:orientation="vertical" >

<Button android:id="@+id/btnStartService"

android:layout_width="270dp"

android:layout_height="wrap_content"

android:text="start_service"/>

<Button android:id="@+id/btnPauseService"

android:layout_width="270dp"

android:layout_height="wrap_content"

android:text="pause_service"/>

<Button android:id="@+id/btnStopService"

android:layout_width="270dp"

android:layout_height="wrap_content"
android:text="stop_service"/>

</LinearLayout>

Relative Layout:
Relative Layout used to specify how child views are positioned relative to each other.
We can arrange components related to each other using id of the components.
To create RelativeLayout we have <RelativeLayout> element in XML.
To arrange components in this layout we have some property like.
android:layout_toRightOf
android:layout_toLeftOf
android:layout_below
android:layout_above
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"

android:layout_width="fill_parent"

android:layout_height="fill_parent"

android:paddingLeft="16dp"

android:paddingRight="16dp" >

<EditText

android:id="@+id/name"

android:layout_width="fill_parent"

android:layout_height="wrap_content"

android:hint="@string/reminder" />

<LinearLayout

android:orientation="vertical"

android:layout_width="fill_parent"

android:layout_height="fill_parent"

android:layout_alignParentStart="true"

android:layout_below="@+id/name">
<Button

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="New Button"

android:id="@+id/button" />

<Button

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="New Button"

android:id="@+id/button2" />

</LinearLayout>

</RelativeLayout>
Table Layout:
TableLayout arrage the components in rows and columns.
To create a table we use <TableLayout> element and to create a row in table we use
<TableRow> element.
<TableRow> contains widgets that we want to display on the screen.
android:collapseColumns: collapse columns attribute is used to collapse or invisible the
column’s of a table layout.
android:stretchColumns: Stretch column attribute is used in Table Layout to change the
default width of a column which is set equal to the width of the widest column but we can also
stretch the columns to take up available free space by using this attribute.
If the value is 1 then the second column is stretched to take up any available space in the row,
because of the column numbers are started from 0.
If the value is 0,1 then both the first and second columns of table are stretched to take up the
available space in the row.
If the value is ‘*’ then all the columns are stretched to take up the available space.

shrinkColumns: Shrink column attribute is used to shrink or reduce the width of the
column‘s. We can specify either a single column or a comma delimited list of column numbers
for this attribute. The content in the specified columns word-wraps to reduce their width.
If the value is 0 then the first column’s width shrinks or reduces by word wrapping its content.
If the value is 0,1 then both first and second columns are shrinks or reduced by word wrapping
its content.

If the value is ‘*’ then the content of all columns is word wrapped to shrink their widths.
<TableLayout xmlns:android="http://schemas.android.com/apk/res/android"

android:layout_width="fill_parent"

android:layout_height="fill_parent">

<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" />

</TableRow>

Frame Layout:
Frame Layout represents a simple layout for the user interface of Android application.
It is usually used for displaying single Views at a specific area on the screen or overlapping its child
views.
Android:gravity property used to arrange components in layout see the below code.

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"

android:layout_width="fill_parent"

android:layout_height="fill_parent">

<ImageView

android:src="@drawable/ic_launcher"

android:scaleType="fitCenter"

android:layout_height="250px"

android:layout_width="250px"/>

<TextView

android:text="Frame Demo"

android:textSize="30px"

android:textStyle="bold"

android:layout_height="fill_parent"

android:layout_width="fill_parent"

android:gravity="center"/>

</FrameLayout>
Absolute Layout:
An Absolute Layout lets you specify exact locations (x/y coordinates) of its children. Absolute
layouts are less flexible and harder to maintain than other types of layouts without absolute
positioning.

android:layout_x
This specifies the x-coordinate of the view.

android:layout_y
This specifies the y-coordinate of the view.
<AbsoluteLayout xmlns:android="http://schemas.android.com/apk/res/android"

android:layout_width="fill_parent"

android:layout_height="fill_parent">

<Button

android:layout_width="100dp"

android:layout_height="wrap_content"

android:text="OK"

android:layout_x="50px"

android:layout_y="361px" />

<Button

android:layout_width="100dp"

android:layout_height="wrap_content"

android:text="Cancel"

android:layout_x="225px"

android:layout_y="361px" />

</AbsoluteLayout>

Android UI Controls:
In android UI or input controls are the interactive or View components that are used
to design the user interface of an application. In android we have a wide variety of UI
or input controls available, those are TextView, EditText, Buttons, Checkbox,
Progressbar, Spinners, etc.

Declare UI Elements in XML:


In android, we can create layouts same as web pages in HTML by using default Views
and ViewGroups in the XML file. The layout file must contain only one root element,
which must be a View or ViewGroup object. Once we define the root element, then
we can add additional layout objects or widgets as a child element to build View
hierarchy that defines our layout.
Load XML Layout File from an Activity:
Once we are done with the creation of layout with UI controls, we need to load the
XML layout resource from our activity onCreate() callback method like as shown
below.

If you observe above code we are calling our layout using setContentView method in
the form of R.layout.layout_file_name. Here our xml file name is activity_main.xml so
we used file name activity_main.

Create UI Element at Runtime


If we want to create UI elements at runtime, we need to create our own custom View
and ViewGroup objects programmatically with required layouts.
Following is the example of creating UI elements (TextView, EditText, Button) in
LinearLayout using custom View and ViewGroup objects in an activity
programmatically.
Android Different Types of UI Controls
We have a different type of UI controls available in android to implement the user
interface for our android applications.
Following are the commonly used UI or input controls in android applications.
TextView EditText AutoCompleteTextView Button ImageButton ToggleButton
CheckBox RadioButton RadioGroup ProgressBar Spinner TimePicker DatePicker
SeekBar AlertDialog Switch RatingBar

Events:
Events are a useful way to collect data about a user’s interaction with interactive
components of our application, like button press or screen touch etc.
The android framework maintains an event queue into which events are placed as they
occur and then each event is removed from the queue on a FIFO basis.
There are three concepts related to Android Event Management:
Event Listeners: the view class is involved in building up an Android GUI, same View
class provides a number of Event Listeners.
The Event Listeners is the object that receives notification when an event happens.
Event Handler Registration: event registration is the process by which an event handler
gets registered with event Listener so that the handler is called when the event
Listener fires the event.
Event Handler: when an event happens the event listener calls the event handler
which is the method that actually handles the event.
Event Handler Event Listener
onClick() OnClickListener()
This is called when the user either click
or touches or focuses upon any widget
like button, text, image etc. you will use
onClick() event handler to handle such
event.
onLongClick() OnLongClickListener()
This is called when the user either click
or touches or focuses upon any widget
like button, text, image etc. you will use
onLongClick() event handler to handle
such event.
OnFocusChange() OnFocusChangeListener()
This us called when the widget loses its
focus means user goes away from the
view item. You will use onFocusChange()
event handler to handle such event.
OnKey() OnTouchListener()
This is called when the user press the
key, release the kry or any movement on
the screen. You will use OnKey() event
hamdler to handle such event.
onMenuItemClick() OnMenuItemClickListener()
This is called when the user selects a
menu item. You will use
onMenuItemClick() event handler to
handle such event.

Event Handler Registration:


Event handler 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 receives
notification when an event happens.
There are three ways to register event handler for any event.
1) Anonymous Inner Class.
2) Lister interface.
3) Layout file.
1) Anonymous Inner Class:
In this method, you need to create an anonymous implementation of the listener class
and each class is applied to only single control.
The advantage of this method is, you can pass arguments to event handler. In this
method, event handler methods access private data of activity. No reference is needed
to call an activity.
But if need to apply the handler to more than one control, you have to write the
separate code for the each handler.
For example if we have two buttons in one activity and we want to use anonymous
inner class method for it than my code is like below.

Java File:
Public class MainActivity extends ActionBarActivity {
@Override
Protected void onCreate(Bundle savedInstanceState)
{
Super.onCreate(savedInstanceState);
setContentView(R.layout.activiy_main);
Button B1 = (Button) findViewById(R.id.b1);
Button B2 = (Button) findViewById(R.id.b2);
B1.setOnClickListerner(new View.OnClickListerner({
@Override
Public void onClick(View v)
{
Toast.makeText(getApplicationContext(),”Button1
Press!!”,Toast.LENGHT_SHORT).show();
}
});
B2.setOnClickListerner(new View.OnClickListerner({
@Override
Public void onClick(View v)
{
Toast.makeText(getApplicationContext(),”Button2
Press!!”,Toast.LENGHT_SHORT).show();
}
});
}
}
2) Listener Interface:
In this method, activity class implements the Listener interface and the event handler
method is implanted inside the activity class.
This method is useful when your application has only a single control of that Listener
type otherwise you will have to do further programming to check which control has
generated event.
For example if we have two buttons in one activity and we want to use anonymous
inner class method for it than my code is like below.
Java File:
Public class MainActivity extends ActionBarActivity implements OnClickListener {
@Override
Protected void onCreate(Bundle savedInstanceState)
{
Super.onCreate(savedInstanceState);
setContentView(R.layout.activiy_main);
Button B1 = (Button) findViewById(R.id.b1);
Button B2 = (Button) findViewById(R.id.b2);
B1.setOnClickListener(this);
B2.setOnClickListener(this);
}
@Override
Public void onClick(View v)
{
If(v.getId() == R.id.b1)
{
Toast.makeText(getApplicationContext(),”Button1
Press!!”,Toast.LENGHT_SHORT).show();
}

If(v.getId() == R.id.b2)
{
Toast.makeText(getApplicationContext(),”Button2
Press!!”,Toast.LENGHT_SHORT).show();
}

}
3) Layout File:
In this method, the event handler method is specified using layout file (.XML file) using
the android:onClick attribute of the view.
The event handler method must have a void return type and take a View as an
argument.
This method does not allow passing argument to listener and for the android
developer it will be difficult to know which method is the handler for which control
until they look into .XML file.
You cannot handle any other event except click event using this method.
XML File:
<RelativeLayout>
<Button
android:id=”@+id/B1”
android:text=”Button 1”
android:onClick=”B1_click” />
<Button
android:id=”@+id/B2”
android:text=”Button 2”
android:onClick=”B2_click” />

</RelativeLayout>

Java File:
Public class MainActivity extends ActionBarActivity implements OnClickListener {
@Override
Protected void onCreate(Bundle savedInstanceState)
{
Super.onCreate(savedInstanceState);
setContentView(R.layout.activiy_main);
}
public void B1_click(View v)
{
Toast.makeText(getApplicationContext(),”Button1
Press!!”,Toast.LENGHT_SHORT).show();
return;
}
public void B2_click(View v)
{
Toast.makeText(getApplicationContext(),”Button2
Press!!”,Toast.LENGHT_SHORT).show();
return;
}
}
Android Tab Layout:
In Android TabLayout is a new element introduced in Design Support library. It
provides horizontal layout to display tabs on the screen. We can display more screens
in a single screen using tabs. We can quickly swipe between the tabs. TabLayout is
basically view class required to be added into our layout(xml) for creating Sliding Tabs.
We use different methods of TabLayout to create, add and manage the tabs.
TabLayout is used to display tabs on the screen. We can create sliding as well as non-
sliding tabs by using TabLayout. If we need simple tabs without sliding then we replace
the layout with the fragment on tab selected listener event and if we need sliding tabs
then we use Viewpager.

Basic TabLayout XML Code:

Important Methods Of TabLayout:


1. newTab(): This method is used to create and return a new TabLayout.Tab.
2. addTab(Tab tab): This method is used to add a tab in the TabLayout.
3. addTab(Tab tab, boolean setSelected): This method is used to add a tab in the
TabLayout and set the state for the tab.
4. addTab(Tab tab, int position): This method is used to add a tab in the
TabLayout and set the state for the tab.
5. getSelectedTabPosition(): This method is used to get the position of the
current selected tab. This method returns an int type value for the position of
the selected tab. It returns -1 if there isn’t a selected tab.
6. getTabAt(int index): This method is used to get the tab at the specified index.
This method returns TabLayout.Tab.
7. getTabCount(): This method is used to get the number of tabs currently
registered with the action bar. This method returns an int type value for the
number of total tabs.
8. 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.
MODE_SCROLLABLE: Scrollable tabs display a subset of tabs at any given moment
and it can contain longer tab labels and a larger number of tabs.
9. removeAllTabs(): This method is used to remove all tabs from the action bar
and deselect the current tab.

Attributes of TabLayout:
1. id: id attribute is used to uniquely identify a TabLayout.
2. support.design:tabBackground: This attribute is used to set the background of the
tabs. We can set a color or drawable in the background of tabs.
3. support.design:tabGravity: This attribute is used to set the gravity to use when
laying out the tabs. We can also set gravity programmatically means in java class using
setTabGravity(int gravity) method.
4. support.design:tabMaxWidth: This attribute is used to set the maximum width for
the tabs.
5. support.design:tabMinWidth: This attribute is used to set the minimum width for
the tabs.
6. support.design:tabMode: This attribute is used to set the behavior mode for the
Tabs in this layout. We can also set the mode programmatically means in java class
using setTabMode(int mode) method.
7. support.design:tabPadding: This attribute is used to set the padding along all edges
of tabs.
8. support.design:tabSelectedTextColor: This attribute is used to set the text color to
be applied to the currently selected tab. We can also set this programmatically using
setTabTextColors(int normalColor, int selectedColor) method.

Android Menu:
Menus are a common user interface component in many types of application.
It android there are two types of menu available context menu and system menu.
Context menu:
When we long press any component in Android at that time this menu is appear.
In android we create a menu item is separate XML file in res->menu folder.
For context menu we have to register android component to this menu using
registerForContextMenu() method it will take object of component for which we want
to set the context menu.
Context menu items will generates onContextItemSelected() event.
Step1: create some menu item in res->menu->XML file.
<menu>
<item
android:id=”@+id/mouse”
android:title=”Mouse” />
<item
android:id=”@+id/keyboard”
android:title=”Keyboard” />
<item
android:id=”@+id/monitor”
android:title=”Monitor” />
</menu>
Step2: implements onCreateContextMenu() method of activity class in .java file
Public void onCreateContextMenu(ContextMenu menu,View v,ContextMenuInfo
menuinfo)
{
super.onCreateContextMenu(menu, v, menuinfo);
MenuInflater mi =getMenuInflater();
mi.inflate(R.menu.context_menu,menu);
}
MenuInflater class used to attach menu to Activity using inflate() method.
Step3: register the EditText for Context menu items using registerForContextMenu()
method.
EditText et = (EditText)findViewById(R.id.txtbox);
registerForContextMenu(et);
Step4: we have onContextItemSelected() method to control the menu item’s
selection event.
Public Boolean onContextItemSelected(MenuItem item) {
et.setText(item.getTitle());
return super.onContextItemSelected(item);
}
Option Menu:
Handset menu items are known as option menu in Android. To create option menu
we need to create separate XML file.
When we click menu button of the device option menu will be appear. Option menu
item will generates onOptionItemSelected() event.
Step1: create some menu item in res->menu->XML file.
<menu>
<item
android:id=”@+id/mouse”
android:title=”Mouse” />
<item
android:id=”@+id/keyboard”
android:title=”Keyboard” />
<item
android:id=”@+id/monitor”
android:title=”Monitor” />
</menu>
Step2: implements onCreateContextMenu() method of activity class in .java file
Public void onCreateContextMenu(ContextMenu menu,View v,ContextMenuInfo
menuinfo)
{
super.onCreateContextMenu(menu, v, menuinfo);
MenuInflater mi =getMenuInflater();
mi.inflate(R.menu.context_menu,menu);
}
MenuInflater class used to attach menu to Activity using inflate() method.
Step3: implement onOptionItemSelected() method to handle the menu selection
event, we can get the ID of selected menu item using item.getItemId() method and
compare it see the below code.
Public boolean onOptionItemSelected(MenuItem item)
{
if(item.getItemId()==R.id.red){ } else
if(item.getItemId()==R.id.green){ } else
if(item.getItemId()==R.id.blue){ }
}
Context Menu System Menu
That menu show by component long Menu show by pressing menu button of
press event android devices.
It provides action that affect the It’s where you should place action that
particular components only like EditText, have a global impact on the app such as
Button etc search and setting
To create context menu To create option menu
onCreateContextMenu() method is used. onCreateOptionMenu() method is used.
When the menu is selected, the When the menu is selected, the
onContextItemSelected() method will onOptionsItemSelected() method will
called by item. called by item
We need to register android widget for No need to register activity for system
Context menu using register menu.
ForContextMenu() method

Recycler View

You might also like