0% found this document useful (1 vote)
151 views36 pages

UNIT 3 MAD Android Widgets

This document provides an overview of Unit 3 of a mobile application development course. It covers fragments and their lifecycles, interaction between fragments, layouts and their types (linear, relative, frame, etc.), adapting to screen orientation changes, using the action bar, common views like buttons and text fields, lists, progress bars, and handling user interface events. It also includes examples of fragments and how they interact using two sample fragments - a menu fragment and text fragment.

Uploaded by

Veeresh Nikee
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (1 vote)
151 views36 pages

UNIT 3 MAD Android Widgets

This document provides an overview of Unit 3 of a mobile application development course. It covers fragments and their lifecycles, interaction between fragments, layouts and their types (linear, relative, frame, etc.), adapting to screen orientation changes, using the action bar, common views like buttons and text fields, lists, progress bars, and handling user interface events. It also includes examples of fragments and how they interact using two sample fragments - a menu fragment and text fragment.

Uploaded by

Veeresh Nikee
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 36

Mobile Application Development

UNIT III
UNIT 3 contents at a glance:

1. Fragments life cycle,


2. Interaction between fragments,
3. Understanding the components of a screen (Layouts),
4. Adapting to display orientation and Managing changes to screen orientation,
5. Utilizing the Action Bar,
6. Working with Views(UI Widgets)-Button,
7. Toast, ToggleButton,
8. CheckBox, RadioButton,
9. Spinner,
10. WebView,
11. EditText,DatePicker,
12. TimePicker, ListView,
13. ProgressBar,
14. Analog and Digital clock,
15. Handling UI events (onClick listeners etc)
16. List fragment, Dialog fragment(prepare programs from lab books)

1. Fragments:
 Android Fragment is the part of activity, it is also known as sub-activity. There can be more
than one fragment in an activity.
 Fragments represent multiple screen inside one activity.
 A activity can contain any number of fragments.
 A fragment is added to a ViewGroup inside the activity. The fragment’s view is displayed
inside this ViewGroup.
 Each fragment has its own life cycle methods that is affected by activity life cycle because
fragments are embedded in activity.
 The FragmentManager class is responsible to make interaction between fragment objects

1
Mobile Application Development

Android Fragment Lifecycle


The lifecycle of android fragment is like the activity lifecycle. There are 12 lifecycle methods for
fragment.

Android Fragment Lifecycle Methods


No. Method Description

1) onAttach(Activity) it is called only once when it is attached with activity.

2) onCreate(Bundle) It is used to initialize the fragment.

onCreateView(LayoutInflater,
3) creates and returns view hierarchy.
ViewGroup, Bundle)

It is invoked after the completion of onCreate()


4) onActivityCreated(Bundle)
method.

It provides information to the fragment that all the


5) onViewStateRestored(Bundle) saved state of fragment view hierarchy has been
restored.

2
Mobile Application Development
6) onStart() makes the fragment visible.

7) onResume() makes the fragment interactive.

8) onPause() is called when fragment is no longer interactive.

9) onStop() is called when fragment is no longer visible.

10) onDestroyView() allows the fragment to clean up resources.

allows the fragment to do final clean up of fragment


11) onDestroy()
state.

It is called immediately prior to the fragment no longer


12) onDetach()
being associated with its activity.

Example for Android Fragments and Interaction Between Fragments:

The MainActivity holds the two fragments TextFragment and MenuFragment

activity_main.xml:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
android:weightSum="1.0">

<fragment
android:layout_height="match_parent"
android:layout_width="match_parent"
class="one.com.fragments.fragments.MenuFragment"
android:id="@+id/fragment"
android:layout_weight="0.5"/>
<fragment
android:layout_width="match_parent"
android:layout_height="match_parent"
class="one.com.fragments.fragments.TextFragment"
android:id="@+id/fragment2"
android:layout_weight="0.5"/>
</LinearLayout>

3
Mobile Application Development

Desired Output Layout:

MenuFragment class 1:

import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import journaldev.com.fragments.R;
public class TextFragment extends Fragment {
TextView text,vers;

@Override

public View onCreateView(LayoutInflater inflater,ViewGroup container, Bundle


savedInstanceState) {

View view = inflater.inflate(R.layout.text_fragment, container, false);


text= (TextView) view.findViewById(R.id.AndroidOs);
vers= (TextView)view.findViewById(R.id.Version);
return view;
}
public void change(String txt, String txt1){
text.setText(txt);
vers.setText(txt1);
}
}

4
Mobile Application Development

text_fragment.xml:

<?xml version="1.0" encoding="utf-8"?>

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:gravity="center"
android:background="#5ba4e5"
android:layout_height="match_parent">

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="40px"
android:textColor="#ffffff"
android:layout_gravity="center"
android:id="@+id/AndroidOs"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:textColor="#ffffff"
android:textSize="30px"
android:id="@+id/Version"/>

</LinearLayout>
TextFragment Class:
The TextFragment comprises of textviews holding the android version name and number.

import android.app.ListFragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ListView;

import one.com.fragments.R;
public class MenuFragment extends ListFragment {
String[] AndroidOS = new String[] {
"Cupcake","Donut","Eclair","Froyo","Gingerbread","Honeycomb","Ice Cream SandWich","Jelly
Bean","KitKat" };
String[] Version = new String[]{"1.5","1.6","2.0-2.1","2.2","2.3","3.0-3.2","4.0","4.1-4.3","4.4"};
@Override

5
Mobile Application Development

public View onCreateView(LayoutInflater inflater,ViewGroup container, Bundle


savedInstanceState) {
View view =inflater.inflate(R.layout.list_fragment, container, false);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActivity(),
android.R.layout.simple_list_item_1, AndroidOS);
setListAdapter(adapter);

return view;

}
@Override
public void onListItemClick(ListView l, View v, int position, long id) {
TextFragment txt = (TextFragment)getFragmentManager().findFragmentById(R.id.fragment2);
txt.change(AndroidOS[position],"Version : "+Version[position]);
getListView().setSelector(android.R.color.holo_blue_dark);
}
}
list_fragment.xml

<?xml version="1.0" encoding="utf-8"?>

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ListView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@android:id/list" />
</LinearLayout>
Understanding the components of a screen (Layouts):
LAYOUTS in android:
 A layout defines the structure for a user interface in your app, such as in an activity.
 All elements in the layout are built using a hierarchy of View and ViewGroup objects.
 A View usually draws something the user can see and interact with. Whereas a ViewGroup
is an invisible container that defines the layout structure for View and other ViewGroup
objects.

6
Mobile Application Development

The View objects are usually called "widgets(Buttons, TextView etc)" and can be one of many
subclasses, such as Button or TextView.
The ViewGroup objects are usually called "layouts(LinearLayout or ConstraintLayout ..etc)" can
be one of many types that provide a different layout structure, such as LinearLayout or
ConstraintLayout .
 Linear Layout
 Relative Layout
 Frame Layout
 Table Layout
 Web View
 List View
 Grid View
 Constraint Layout

Android Layout Attributes

Android Layout Types


We have a different type of layouts available in android to implement user interface for our
android applications with different designs based on our requirements.Following are the
commonly used layouts in android applications to implement required designs.

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

7
Mobile Application Development

Android Linear Layout

In android, LinearLayout is a ViewGroup subclass which is used to render all child View instances
one by one either in horizontal direction or vertical direction based on the orientation property.

Example:
<?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:paddingLeft="20dp"
android:paddingRight="20dp"
android:orientation="vertical" >
<EditText
android:id="@+id/txtTo"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="To"/>
<EditText
android:id="@+id/txtSub"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Subject"/>
<EditText
android:id="@+id/txtMsg"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:gravity="top"
android:hint="Message"/>
<Button
android:layout_width="100dp"
android:layout_height="wrap_content"
android:layout_gravity="right"

8
Mobile Application Development
android:text="Send"/>
</LinearLayout>
Output:

Android Relative Layout

In android, RelativeLayout is a ViewGroup which is used to specify the position of child View
instances relative to each other (Child A to the left of Child B) or relative to the parent (Aligned to
the top of parent).

9
Mobile Application Development

Example for relative layout:


<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="10dp"
android:paddingRight="10dp">
<Button
android:id="@+id/btn1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:text="Button1" />
<Button
android:id="@+id/btn2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_centerVertical="true"
android:text="Button2" />
<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
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"

10
Mobile Application Development
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>
Output:

Android Frame Layout

In android, FrameLayout is a ViewGroup subclass which is used to specify the position of View
instances it contains on the top of each other to display only single View inside the FrameLayout.
In android, FrameLayout will act as a placeholder on the screen and it is used to hold a single child
view.
we can say FrameLayout is designed to block out an area on the screen to display a single item.
In FrameLayout, the child views are added in a stack and the most recently added child will show
on the top. We can add multiple children views to FrameLayout and control their position by using
gravity attributes in FrameLayout.

11
Mobile Application Development

Android FrameLayout Example

XML File:
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<ImageView
android:id="@+id/imgvw1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:scaleType="centerCrop"
android:src="@drawable/flimg" />
<TextView
android:id="@+id/txtvw1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="40dp"
android:background="#4C374A"
android:padding="10dp"
android:text="Grand Palace, Bangkok"
android:textColor="#FFFFFF"
android:textSize="20sp" />
<TextView
android:id="@+id/txtvw2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="right|bottom"
android:background="#AA000000"
android:padding="10dp"
android:text="21/Aug/2017"
android:textColor="#FFFFFF"
android:textSize="18sp" />
</FrameLayout>

12
Mobile Application Development

Output of Android FrameLayout Example

When we run above example using android virtual device (AVD) we will get a result like as shown
below.

Android Table Layout

In android, TableLayout is a ViewGroup subclass which is used to display the child View elements in
rows and columns.
Following is the pictorial representation of table layout in android applications.

In android, TableLayout will position its children elements into rows and columns and it won’t
display any border lines for rows, columns or cells.

13
Mobile Application Development

Example for table layout:

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>


<TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginTop="100dp"
android:paddingLeft="10dp"
android:paddingRight="10dp" >
<TableRow android:background="#0079D6" android:padding="5dp">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="UserId" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="User Name" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Location" />
</TableRow>
<TableRow android:background="#DAE8FC" android:padding="5dp">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="1" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Suresh Dasari" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Hyderabad" />
</TableRow>
<TableRow android:background="#DAE8FC" android:padding="5dp">

14
Mobile Application Development
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="2" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Rohini Alavala" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Guntur" />
</TableRow>
<TableRow android:background="#DAE8FC" android:padding="5dp">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="3" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Trishika Dasari" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Guntur" />
</TableRow>
</TableLayout>

Output of Android TableLayout Example


When we run above example using android virtual device (AVD) we will get a result like as shown
below.

15
Mobile Application Development

Android Web View

In android, WebView is a browser which is used to display the web pages as a part of our activity
layout.
in android the WebView will act as an embedded browser to include the web pages content in our
activity layout and it won’t contain any features of normal browser, such as address bar, navigation
controls, etc.

Following is the pictorial representation of WebView in android applications.

activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<WebView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/webview"
android:layout_width="fill_parent"
android:layout_height="fill_parent" />

MainActivity.java

package com.tutlane.webview;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.webkit.WebView;

public class MainActivity extends AppCompatActivity {


@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
WebView wv = (WebView) findViewById(R.id.webview);
String customHtml = "<html><body><h1>Welcome to Tutlane</h1>" +

16
Mobile Application Development
"<h2>Welcome to Tutlane</h2><h3>Welcome to Tutlane</h3>" +
"<p>It's a Static Web HTML Content.</p>" +
"</body></html>";
wv.loadData(customHtml, "text/html", "UTF-8");
}
}

Output of Android WebView Example

When we run above example using android virtual device (AVD) we will get a result like as shown
below.

This is how we can show the static HTML content using WebView in android applications

Android List View

In android, ListView is a ViewGroup which is used to display scrollable single column list of items.
ListView is a ViewGroup which is used to display the list of scrollable of items in multiple rows and
the list items are automatically inserted to the list using an adapter.

Generally, the adapter pulls data from a sources such as an array or database and converts each
item into a result view and that’s placed into the list.

Following is the pictorial representation of listview in android applications.

17
Mobile Application Development

Android Grid View

In android, GridView is a ViewGroup which is used to display items in a scrollable grid of columns
and rows.
grid items are automatically inserted to the gridview layout using a list adapter.

Generally, the adapter pulls data from a sources such as an array or database and converts each
item into a result view and that’s placed into the list.

Following is the pictorial representation of GridView in android applications.

Example for GridView:


activity_main.xml

<?xml version="1.0" encoding="utf-8"?>


<GridView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/gridview"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:columnWidth="110dp"
android:numColumns="auto_fit"
android:verticalSpacing="10dp"
android:horizontalSpacing="10dp"
android:stretchMode="columnWidth"
android:gravity="center" />

18
Mobile Application Development

Android Constraint Layout:

Android ConstraintLayout is used to define a layout by assigning constraints for every child
view/widget relative to other views present.
A ConstraintLayout is similar to a RelativeLayout, but with more power. The aim of
ConstraintLayout is to improve the performance of the applications by removing the nested views
with a flat and flexible design.
A ConstraintLayout is a android.view.ViewGroup which allows you to position and size widgets in a
flexible way.
Note: ConstraintLayout is available as a support library that you can use on Android systems
starting with API level 9 (Gingerbread). As such, we are planning on enriching its API and
capabilities over time. This documentation will reflect those changes.
There are currently various types of constraints that you can use:

 Relative positioning
 Margins
 Centering positioning
 Circular positioning
 Visibility behavior
 Dimension constraints
 Chains
 Virtual Helpers objects
 Optimizer

Adapting to display orientation in android:

Android supports two screen orientations:


1. portrait and
2. landscape.
When the screen orientation of an Android device is changed, the current activity being displayed is
destroyed and re-created automatically to redraw its content in the new orientation.
There are two ways to handle changes in screen orientation:
 Anchoring controls—Set the controls to appear at the places relative to the four edges of the
screen. When the screen orientation changes, the controls do not disappear but are rearranged
relative to the four edges.
 Defining layout for each mode—A new layout file is defined for each of the two screen
orientations. One has the controls arranged to suit the Portrait mode, and the other has the
controls arranged to suit the Landscape mode.
portrait:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
</RelativeLayout>

19
Mobile Application Development

landscape:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="match_parent">

</RelativeLayout>

second approach to display orientation:

Defining Layout for Each Mode


Here we have to create 2 activities in vertical and horizontal orientations for each screen in
application.

Managing Changes to screen orientation:

There are a different options to handle the orientation changes:


1. Lock screen orientation
2. Prevent Activity to recreated
3. Save basic state
4. Save complex objects

For explanation of above options, go to below URL:


https://android.jlelse.eu/handling-orientation-changes-in-android-7072958c442a

20
Mobile Application Development

Android Widgets:
There are given a lot of android widgets with simplified examples such as Button, EditText,
AutoCompleteTextView, ToggleButton, DatePicker, TimePicker, ProgressBar etc.

Android Button:

Android Button represents a push-button. The android.widget.Button is subclass of TextView class


and CompoundButton is the subclass of Button class.
Working with button:
//code to display the sum of two numbers
package com.example.com.sum;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {


private EditText edittext1, edittext2;
private Button buttonSum;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
addListenerOnButton();
}
public void addListenerOnButton() {
edittext1 = (EditText) findViewById(R.id.editText1);
edittext2 = (EditText) findViewById(R.id.editText2);
buttonSum = (Button) findViewById(R.id.button);
buttonSum.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
String value1=edittext1.getText().toString();
String value2=edittext2.getText().toString();
int a=Integer.parseInt(value1);
int b=Integer.parseInt(value2);
int sum=a+b;

21
Mobile Application Development
Toast.makeText(getApplicationContext(),String.valueOf(sum), Toast.LENGTH_LONG).show();
}
}); } }

Android Toast:
Andorid Toast can be used to display information for the short period of time. A toast contains
message to be displayed quickly and disappears after sometime.
The android.widget.Toast class is the subclass of java.lang.Object class.
You can also create custom toast as well for example toast displaying image. You can visit next page
to see the code for custom toast.

Toast class:
Toast class is used to show notification for a particular interval of time. After sometime it
disappears. It doesn't block the user interaction.

Constants of Toast class:


There are only 2 constants of Toast class.

1. public static final int LENGTH_LONG : displays view for the long duration of time.
2. public static final int LENGTH_SHORT : displays view for the short duration of time.

Methods of Toast class:


1. public static Toast makeText(Context context, CharSequence text, int duration) : makes the toast
containing text and duration.
2. public void show() : displays toast.
3. public void setMargin (float horizontalMargin, float verticalMargin) : changes the horizontal and
vertical margin difference.

Working with Toast:


// code to display the toast
package com.example.toast;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Displaying Toast with Hello message

22
Mobile Application Development
Toast.makeText(getApplicationContext(),"Hello ",Toast.LENGTH_SHORT).show();
}
}

Android ToggleButton:
Android Toggle Button can be used to display checked/unchecked (On/Off) state on the button.
It is beneficial if user have to change the setting between two states. It can be used to On/Off
Sound, Wifi, Bluetooth etc.
Since Android 4.0, there is another type of toggle button
called switch that provides slider control.
Android ToggleButton and Switch both are the subclasses of
CompoundButton class.

The 3 XML attributes of ToggleButton class.

1. android:disabledAlpha : Returns the text when button is not in the


checked state.
2. android:textOff : The text for the button when it is not checked.
3. android:textOn : The text for the button when it is checked.

Methods of ToggleButton class :

1. CharSequence getTextOff() : Returns the text when button is not in the checked state.
2. CharSequence getTextOn() : Returns the text for when button is in the checked state.
3. void setChecked(boolean checked) : Changes the checked state of this button.

Working with ToggleButton:


// code to check which toggle button is ON/OFF
Package com.example.togglebutton;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import android.widget.ToggleButton;
public class MainActivity extends AppCompatActivity {
private ToggleButton toggleButton1, toggleButton2;
private Button buttonSubmit;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);

23
Mobile Application Development
setContentView(R.layout.activity_main);
addListenerOnButtonClick();
}
public void addListenerOnButtonClick(){
//Getting the ToggleButton and Button instance from the layout xml file
toggleButton1=(ToggleButton)findViewById(R.id.toggleButton);
toggleButton2=(ToggleButton)findViewById(R.id.toggleButton2);
buttonSubmit=(Button)findViewById(R.id.button);

//Performing action on button click


buttonSubmit.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View view) {
StringBuilder result = new StringBuilder();
result.append("ToggleButton1 : ").append(toggleButton1.getT
ext());
result.append("\nToggleButton2 : ").append(toggleButton2.ge
tText());
//Displaying the message in toast
Toast.makeText(getApplicationContext(), result.toString(),Toas
t.LENGTH_LONG).show();
}
}); } }

Android CheckBox:

Android CheckBox is a type of two state button either checked or


unchecked.
There can be a lot of usage of checkboxes. For example, it can be used
to know the hobby of the user, activate/deactivate the specific action
etc.
Android CheckBox class is the subclass of CompoundButton class.
Android CheckBox is a type of two state button either checked or
unchecked.
There can be a lot of usage of checkboxes. For example, it can be used
to know the hobby of the user, activate/deactivate the specific action etc.Android CheckBox class is
the subclass of CompoundButton class.
Methods of CheckBox class:
There are many inherited methods of View, TextView, and Button classes in the CheckBox class.
1. public boolean isChecked() : Returns true if it is checked otherwise false.
2. public void setChecked(boolean status) : Changes the state of the CheckBox.

24
Mobile Application Development

Android CheckBox Example:


//code to display checked items
Package com.example.checkbox;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
CheckBox pizza,coffe,burger;
Button buttonOrder;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
addListenerOnButtonClick();
}
public void addListenerOnButtonClick(){
//Getting instance of CheckBoxes and Button from the activty_main.xml file
pizza=(CheckBox)findViewById(R.id.checkBox);
coffe=(CheckBox)findViewById(R.id.checkBox2);
burger=(CheckBox)findViewById(R.id.checkBox3);
buttonOrder=(Button)findViewById(R.id.button);
//Applying the Listener on the Button click
buttonOrder.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View view) {
int totalamount=0;
StringBuilder result=new StringBuilder();
result.append("Selected Items:");
if(pizza.isChecked()){
result.append("\nPizza 100Rs");
totalamount+=100;
}
if(coffe.isChecked()){
result.append("\nCoffe 50Rs");
totalamount+=50;
}
if(burger.isChecked()){
result.append("\nBurger 120Rs");
totalamount+=120;
}

25
Mobile Application Development
result.append("\nTotal: "+totalamount+"Rs");
//Displaying the message on the toast
Toast.makeText(getApplicationContext(), result.toString(), Toast.LENGTH_LONG).show();
}
}); } }

Android RadioButton:
RadioButton is a two states button which is either checked or unchecked. If a single radio button is
unchecked, we can click it to make checked radio button. Once a radio button is checked, it cannot
be marked as unchecked by user.RadioButton is generally used with RadioGroup. RadioGroup
contains several radio buttons, marking one radio button as checked makes all other radio buttons
as unchecked.
Example of Radio Button:
Package com.example.radiobutton;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
Button button;
RadioButton genderradioButton;
RadioGroup radioGroup;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
radioGroup=(RadioGroup)findViewById(R.id.radioGroup);
}
public void onclickbuttonMethod(View v){
int selectedId = radioGroup.getCheckedRadioButtonId();
genderradioButton = (RadioButton) findViewById(selectedId);
if(selectedId==-1){
Toast.makeText(MainActivity.this,"Nothing selected", Toast.LENGTH_SHORT).show();
}
else{
Toast.makeText(MainActivity.this,genderradioButton.getText(), Toast.LENGTH_SHORT).show
();
} } }

26
Mobile Application Development

Android Spinner:
Android Spinner is like the combox box of AWT or Swing. It can be
used to display the multiple options to the user in which only one
item can be selected by the user.Android spinner is like the drop
down menu with multiple values from which the end user can
select only one value.Android spinner is associated with
AdapterView. So you need to use one of the adapter classes with
spinner.
Android Spinner class is the subclass of AbsSpinner class.

Android Spinner Example:

// code to display item on the spinner and perform event handling


package com.example.spinner;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity implements
AdapterView.OnItemSelectedListener {
String[] country = { "India", "USA", "China", "Japan", "Other"};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Getting the instance of Spinner and applying OnItemSelectedListener on it
Spinner spin = (Spinner) findViewById(R.id.spinner);
spin.setOnItemSelectedListener(this);

//Creating the ArrayAdapter instance having the country list

ArrayAdapter aa = new ArrayAdapter(this,android.R.layout.simple_spinner_item,country);


aa.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
//Setting the ArrayAdapter data on the Spinner
spin.setAdapter(aa);

27
Mobile Application Development
//Performing action onItemSelected and onNothing selected
@Override
public void onItemSelected(AdapterView<?> arg0, View arg1, int position, long id) {
Toast.makeText(getApplicationContext(),country[position] , Toast.LENGTH_LONG).show();
}
@Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub } }

Android WebView:
Android WebView is used to display web page in android. The web page can be loaded from same
application or URL. It is used to display online content in android activity.Android WebView uses
webkit engine to display web page.
The android.webkit.WebView is the subclass of AbsoluteLayout class.
The loadUrl() and loadData() methods of Android WebView class are used to load and display web
page.

Android WebView Example:


package com.example.webview;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.webkit.WebView;

public class MainActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
WebView mywebview = (WebView) findViewById(R.id.we
bView);
String data = "<html><body><h1>Hello, Javatpoint!</h1>
</body></html>";
mywebview.loadData(data, "text/html", "UTF-8");

mywebview.loadData(data,”UTF-8”);
} }

Android DatePicker:

Android DatePicker is a widget to select date. It allows you to select date by day, month and year.
Like DatePicker, android

28
Mobile Application Development
also provides TimePicker to select time.
The android.widget.DatePicker is the subclass of FrameLayout class.

Android DatePicker Example:


Package com.example.datepicker;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {


DatePicker picker;
Button displayDate;
TextView textview1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

textview1=(TextView)findViewById(R.id.textView1);
picker=(DatePicker)findViewById(R.id.datePicker);
displayDate=(Button)findViewById(R.id.button1);

textview1.setText("Current Date: "+getCurrentDate());

displayDate.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View view) {

textview1.setText("Change Date: "+getCurrentDate());


} }); }
public String getCurrentDate(){
StringBuilder builder=new StringBuilder();;
builder.append((picker.getMonth() + 1)+"/");//month is 0 based
builder.append(picker.getDayOfMonth()+"/");
builder.append(picker.getYear());
return builder.toString();
} }

29
Mobile Application Development

Android TimePicker:
Android TimePicker widget is used to select date. It allows you to select time by hour and minute.
You cannot select time by seconds.
The android.widget.TimePicker is the subclass of FrameLayout class.
Android TimePicker Example:
package com.example.timepicker;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.TimePicker;
public class MainActivity extends AppCompatActivity {
TextView textview1;
TimePicker timepicker;
Button changetime;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textview1=(TextView)findViewById(R.id.textView1);
timepicker=(TimePicker)findViewById(R.id.timePicker);
//Uncomment the below line of code for 24 hour view
timepicker.setIs24HourView(true);
changetime=(Button)findViewById(R.id.button1);
textview1.setText(getCurrentTime());
changetime.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View view) {
textview1.setText(getCurrentTime());
} }); }
public String getCurrentTime(){
String currentTime="Current Time: "+timepicker.getCurrentHour()+":"+timepicker.getCurrentMin
ute();
return currentTime;
} }

30
Mobile Application Development

Android Analog clock and Digital clock :


The android.widget.AnalogClock and android.widget.DigitalClock classes provides the
functionality to display analog and digital clocks.
Android analog and digital clocks are used to show time in android application.
Android AnalogClock is the subclass of View class.
Android DigitalClock is the subclass of TextView class.

Working with analog and digital clocks:


Activity_main.xml:
Drag and drop analog and digital clocks onto the layout.
<AnalogClock
android:id="@+id/analogClock1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginLeft="136dp"
android:layout_marginTop="296dp"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<DigitalClock
android:id="@+id/digitalClock1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/analogClock1"
android:layout_centerHorizontal="true"
android:layout_marginLeft="176dp"
android:layout_marginTop="84dp"
android:text="DigitalClock"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />

MainActivity.java:
package com.example.analogdigital;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);

31
Mobile Application Development
setContentView(R.layout.activity_main);
} }

Android ProgressBar:
We can display the android progress bar dialog box to display the status of work being done e.g.
downloading file, analyzing status of work etc..
android.app.ProgressDialog class is used to show the progress bar. Android ProgressDialog is the
subclass of AlertDialog class.
The ProgressDialog class provides methods to work on progress bar like setProgress(),
setMessage(), setProgressStyle(), setMax(), show() etc. The progress range of Progress Dialog is 0 to
10000.

ProgressBar Example:
MainActivity.java:
package example.gb.progressbarexample;
import android.graphics.Color;
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.ProgressBar;
import android.widget.Button;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// initiate progress bar and start button
final ProgressBar simpleProgressBar = (ProgressBar) findViewById(R.id.simpleProgressBar);
Button startButton = (Button) findViewById(R.id.startButton);
// perform click event on button
startButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// visible the progress bar
simpleProgressBar.setVisibility(View.VISIBLE);
} });}}

32
Mobile Application Development

Android ListView:
Android ListView is a view which contains the group of items and displays in a scrollable list.
ListView is implemented by importing android.widget.ListView class. ListView is a default scrollable
which does not use other scroll view.
ListView uses Adapter classes which add the content from data source (such as string array, array,
database etc) to ListView. Adapter bridges data between an AdapterViews and other Views
(ListView, ScrollView etc).
Example of ListView:

strings.xml:
<resources>
<string name="app_name">ListView</string>
<string-array name="array_technology">
<item>Android</item>
<item>Java</item>
<item>Php</item>
<item>Hadoop</item>
<item>Sap</item>
<item>Python</item>
<item>Ajax</item>
<item>C++</item>
<item>Ruby</item>
<item>Rails</item>
<item>.Net</item>
<item>Perl</item>
</string-array>
</resources>

MainActivity.java:
Package com.example.listview;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
ListView listView;
TextView textView;
String[] listItem;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);

33
Mobile Application Development
setContentView(R.layout.activity_main);

listView=(ListView)findViewById(R.id.listView);
textView=(TextView)findViewById(R.id.textView);
listItem = getResources().getStringArray(R.array.array_technology);
final ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, android.R.id.text1, listItem);
listView.setAdapter(adapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
// TODO Auto-generated method stub
String value=adapter.getItem(position);
Toast.makeText(getApplicationContext(),value,Toast.LENGTH_SHORT).show(); } }); }
}

Android EditText:
Android system supports EditText, which is a subclass of TextView supplied with text editing
operations. We often use EditText in our Android applications in order to provide an input or text
field, especially in forms.
EditText in layout file:
<EditText
android:id="@+id/Username"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:ems="10"
android:hint="Username"
android:inputType=”text” />

EditText Example:
MainActivity.java:
package com.example.demo;
import android.os.Bundle;
import android.app.Activity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class MainActivity extends Activity {
EditText eText;
Button btn;
@Override
protected void onCreate(Bundle savedInstanceState) {

34
Mobile Application Development
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
eText = (EditText) findViewById(R.id.edittext);
btn = (Button) findViewById(R.id.button);
btn.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
String str = eText.getText().toString();
Toast msg = Toast.makeText(getBaseContext(),str,Toast.LENGTH_LONG);
msg.show();
} });}}

List Fragment:

A fragment that displays a list of items by binding to a data source such as an array or Cursor, and
exposes event handlers when the user selects an item.
ListFragment hosts a ListView object that can be bound to different data sources, typically either an
array or a Cursor holding query results. Binding, screen layout, and row layout are discussed in the
following sections.

Example:

Dialog Fragment:
A fragment that displays a dialog window, floating on top of its activity's window. This fragment
contains a Dialog object, which it displays as appropriate based on the fragment's state. Control of
the dialog (deciding when to show, hide, dismiss it) should be done through the API here, not with
direct calls on the dialog.

35
Mobile Application Development

36

You might also like