0% found this document useful (0 votes)
15 views22 pages

Unit Iv

Unit IV of the Mobile Application Development course covers various selection widgets like ListView, Spinner, and GridView, along with debugging tools such as the Dalvik Debug Monitor Service (DDMS). It provides practical examples for implementing these controls in Android applications, including code snippets for creating and managing user interfaces. Additionally, it discusses the functionalities of DDMS for debugging and monitoring application performance.

Uploaded by

hareeshmajnu1
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 (0 votes)
15 views22 pages

Unit Iv

Unit IV of the Mobile Application Development course covers various selection widgets like ListView, Spinner, and GridView, along with debugging tools such as the Dalvik Debug Monitor Service (DDMS). It provides practical examples for implementing these controls in Android applications, including code snippets for creating and managing user interfaces. Additionally, it discusses the functionalities of DDMS for debugging and monitoring application performance.

Uploaded by

hareeshmajnu1
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/ 22

Mobile Application Development Unit-IV

Unit 4: Using Selection widgets and Debugging

Using List View, Using the Spinner control, Using the GridView Control, Creating anImage Gallery
Using the ViewPager Control
Using the Debugging Tool:Dalvik DebugMonitor Service(DDMS), Debugging Application, Using
the Debug Perspective.
Displaying And Fetching Information Using Dialogs and Fragments: What AreDialogs?, Selecting
the Date and Time in One Application, Fragments, CreatingFragments with java Code, Creating
Special Fragments

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
Let's implement a simple listview example.

Structure of listview project

Page 1
Mobile Application Development Unit-IV

activity_main.xml
First we need to drag and drop ListView component from palette to activity_main.xml file.

File: activity_main.xml

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


<android.support.constraint.ConstraintLayoutxmlns:android="http://schemas.android.c
om/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="in.kvsw.listview.MainActivity">
<ListView
android:id="@+id/listView"
android:layout_width="match_parent"
android:layout_height="fill_parent"
/>
</android.support.constraint.ConstraintLayout>

Create an additional mylist.xml file in layout folder which contains view components displayed in
listview.
File: mylist.xml
<?xml version="1.0" encoding="utf-8"?>
<TextViewxmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Medium Text"
android:textStyle="bold"
android:textAppearance="?android:attr/textAppearanceMedium"
android:layout_marginLeft="10dp"
android:layout_marginTop="5dp"
android:padding="2dp"
android:textColor="#4d4d4d"
/>
Now place the list of data in strings.xml file by creating string-array.
strings.xml
File: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>

Page 2
Mobile Application Development Unit-IV

<item>Python</item>
<item>Ajax</item>
<item>C++</item>
<item>Ruby</item>
<item>Rails</item>
<item>.Net</item>
<item>Perl</item>
</string-array>
</resources>
Activity class
In java class we need to add adapter to listview using setAdapter() method of listview.
File: MainActivity.java
package in.kvsw.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 MainActivityextends AppCompatActivity


{
ListViewlistView;
TextViewtextView;
String[] listItem;
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
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, intposition, long l)
{
// TODO Auto-generated method stub
String value=adapter.getItem(position);
Toast.makeText(getApplicationContext(),value,Toast.LENGTH_SHORT).show();

}
});
}
}

Page 3
Mobile Application Development Unit-IV

Output

Spinner Control
Android Spinner is like the combo 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.
In this Application, we are going to display the country list. You need to use ArrayAdapter class to store
the country list.
Let's see the simple example of spinner in android.
activity_main.xml
Drag the Spinner from the pallete, now the activity_main.xml file will like this:
File: activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayoutxmlns:android="http://schemas.andro
id.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"

Page 4
Mobile Application Development Unit-IV

xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="in.kvsw.spinner.MainActivity">

<Spinner
android:id="@+id/spinner"
android:layout_width="149dp"
android:layout_height="40dp"
android:layout_marginBottom="8dp"
android:layout_marginEnd="8dp"
android:layout_marginStart="8dp"
android:layout_marginTop="8dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.502"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.498" />

</android.support.constraint.ConstraintLayout>

Activity class
Let's write the code to display item on the spinner and perform event handling.
File: MainActivity.java
package in.kvsw.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 MainActivityextends 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
ArrayAdapteraa = 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);
}

Page 5
Mobile Application Development Unit-IV

//Performing action onItemSelected and onNothing selected


@Override
public void onItemSelected(AdapterView<?> arg0, View arg1, intposition, long id)
{
Toast.makeText(getApplicationContext(),country[position] ,
Toast.LENGTH_LONG).show();
}
@Override
public void onNothingSelected(AdapterView<?> arg0)
{
// TODO Auto-generated method stub
}
}
Output:

USING THE GRIDVIEW CONTROL


The GridView control is a ViewGroup used to display text and image data in the form of a
rectangular, scrollable grid.
To display data in the grid, we first define a GridView control in the XML layout, and then bind
the data that we want to be displayed to it using the ArrayAdapter.

Page 6
Mobile Application Development Unit-IV

As the name suggests, ViewGroup is a view that contains other views known as child views.
The ViewGroup class is a base class for layout managers that are used to contain and arrange several
views. ListView, GridView, and other container controls are good examples of ViewGroups.
<LinearLayoutxmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextViewandroid:id="@+id/selectedopt"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Select a fruit " />
<GridViewandroid:id="@+id/grid"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:verticalSpacing="2dip"
android:horizontalSpacing="5dip"
android:numColumns="auto_fit"
android:columnWidth="130dip"
android:stretchMode="columnWidth"
android:gravity="center" />
</LinearLayout>

Let’s take a look at the different attributes used in GridView.


GridView Attributes
The number of rows displayed through GridView is dependent on the number of elements supplied by the
attached adapter. The size and number of columns is controlled through the following attributes:
• android:numColumns—Defines the number of columns. If we supply a value, auto_fit, Android
computes the number of columns based on available space.
• android:verticalSpacing and android:horizontalSpacing—Define the amount of whitespace between
the items in the grid.
• android:columnWidth—Defines the width of each column.
• android:stretchMode—The attribute determines whether the column can stretch or expand to take up
the available space. The valid values for this attribute are
• none—Does not allow columns to stretch or expand
• columnWidth—Makes the columns take up all available space
• spacingWidth—Makes the whitespace between columns take up all available space
File: MainActivity.java
package in.kvsw.gridview;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.TextView;
import android.widget.GridView;
import android.widget.ArrayAdapter;
import android.widget.AdapterView;
import android.view.View;

Page 7
Mobile Application Development Unit-IV

public class MainActivityextends AppCompatActivity implements


AdapterView.OnItemClickListener
{
TextViewselectedOpt;
String[] fruits={"Apple", "Mango", "Banana", "Grapes", "Orange",
"Pineapple",
"Strawberry", "Papaya", "Guava", "Pomegranate", "Watermelon", "Chickoo",
"Dates",
"Plum", "Cherry", "Kiwi"};
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
selectedOpt=(TextView) findViewById(R.id.selectedopt);
GridView g=(GridView) findViewById(R.id.grid);
ArrayAdapter<String>arrayAdpt=new ArrayAdapter<String> (this,
android.R.layout.simple_list_item_1, fruits);
g.setAdapter(arrayAdpt);
g.setOnItemClickListener(this);
}
public void onItemClick(AdapterView<?> parent, View v, intposition, long id)
{
selectedOpt.setText("You have selected "+fruits[position]);
}
public void onNothingSelected(AdapterView<?> parent)
{
selectedOpt.setText("");
}
}
Output:

Page 8
Mobile Application Development Unit-IV

USING THE DEBUGGING TOOL: DALVIK DEBUG MONITOR


SERVICE (DDMS)
The DDMS is a powerful debugging tool that is downloaded as part of the Android SDK. DDMS can be
run by selecting the Tools->Android->Android Device Monitor->DDMS icon on the top-right corner of
the Android Device Monitor.
When we run DDMS, it automatically connects to the attached Android device or any running
emulator. DDMS helps with a variety of tasks, including
• Finding bugs in applications running either on an emulator or on the physical device.
• Providing several services such as port forwarding, on-device screen capture, incoming call, SMS, and
location data spoofing.
• Showing the status of active processes, viewing the stack and heap, viewing the status of active threads,
and exploring the file system of any active emulator.
• Providing the logs generated by LogCat, so we can see log messages about the state of the application
and the device. LogCat displays the line number on which the error(s) occurred.
• Simulating different types of networks, such as GPRS and EDGE.
DDMS tool window.

In the upper-left pane of the DDMS window, we see a Devices tab that displays the list of Android
devices connected to your PC, along with the running AVDs (if any). The VMs associated with each
device or AVD also is displayed. Selecting a VM displays its information in the right pane. In
the Devices tab, you see some icons, described here:
• Debug—Used to debug the selected process.
• Update Heap—Enables heap information of the process. After clicking this icon, use the Heap icon on
the right pane to get heap information.
• Dump HPROF file—Shows the HPROF file that can be used for detecting memory leaks.
• Cause GC—Invokes Garbage Collection.

Page 9
Mobile Application Development Unit-IV

• Update Threads—Enables fetching the thread information of the selected process. After clicking this
icon, we need to click the Threads icon in the right pane to display information about the threads that are
created and destroyed in the selected process.
• Start Method Profiling—Used to find the number of times different methods are called in an
application and the time consumed in each of them. Click the Start Method Profiling icon, interact with
the application, and click the Stop Method Profiling icon to obtain information related to the different
methods called in the application.
• Stop Process—Stops the selected process.
• Screen Capture—Captures our device/emulator screen. If the application is running and its output is
being displayed through the device/emulator, clicking the Screen Capture icon displays the Device Screen
Capture dialog box, as shown in Figure-(left). The text, Capturing, tells us that the output of the
application or image being displayed in the device/emulator is in the process of being captured. Once the
image is captured, it is displayed as shown in Figure-(right).

Image shown in the device/emulator is being captured (left), and the captured image of the
device/emulator displayed (right)

The meaning of the buttons shown at the top in the Device Screen Capture dialog box is shown here:
• Refresh—Updates the captured image.
• Rotate—With each click of this button, the captured image rotates 90 degrees in the counterclockwise
direction.
• Save—Saves the captured image as a .png file.
• Copy—Copies the captured image to the clipboard.
• Done—Closes the Device Screen Capture dialog.
Back to DDMS, on the right pane (refer above Figure), we find the following tabs:
• Threads—Displays information about the threads within each process, as shown in above Figure (left).
The following information about the threads is displayed:
• Thread ID—Displays the unique ID assigned to each thread
• Status—Displays the current status of the thread—whether it is in running, sleeping, starting, waiting,
native, monitor, or zombie state
• utime—Indicates the cumulative time spent executing user code

Page 10
Mobile Application Development Unit-IV

• stime—Indicates the cumulative time spent executing system code


• Name—Displays the name of the thread
• Heap—Displays the heap information of the process (provided the Update Heap button from
the Devices tab has been clicked). Select the Cause GC button to begin the garbage collection process.
The object types and the size of memory allocated to them are displayed. After we select an object type, a
bar graph is displayed, showing the number of objects allocated for a particular memory size in bytes
(see Figure—right).

The Threads tab, displaying information about running threads (left), and the Heap tab displaying heap
information of the current process (right)
• Allocation Tracker—Tracks the objects allocated to an application. Click the Start Trackingbutton,
interact with the application, and then click Get Allocations to see the list of objects allocated to the
application (see Figure—left). After we click the Get Allocations button again, the newly allocated
objects are added to the earlier displayed list of allocated objects. We can also click the Stop
Tracking button to clear the data and restart.

The Allocation Tracker tab, which tracks objects allocated to the application (left) and the File
Explorer tab, displaying the file system on the device/emulator (right)

• Network Statistics—Helps us in getting information regarding network usage of our application, that
is, when our app made network requests, speed of data transfer—and other related information.
• File Explorer—Displays the file system on the device, as shown in Figure (right). We can view and
delete files on the device/emulator through this tab. We can even push or pull files from the device using
the two icons, Pull a file from the device and Push a file onto the device, that are shown at the top. To
copy a file from the device, select the file in the File Explorer and click the Pull a file from the
device button. The Get Device File dialog box opens up, prompting us to specify the path and filename
where we want to store the pulled device file. Similarly, to copy a file to the device, click the Push file
onto the device button in the File Explorer tab. The Put File on Device dialog box opens up, letting us
browse the local disk drive. Select the file we want to copy to the device and click Open button to copy it
to the device.
Page 11
Mobile Application Development Unit-IV

Right of the File Explorer tab is the Emulator Control tab that can be used to simulate incoming phone
calls, SMS messages, or GPS coordinates. To simulate an incoming phone call, select the Voice option,
provide the incoming phone number, and click the Call button, as shown in Figure (left). In the emulator,
an incoming call appears, prompting the user to answer the call in Figure (right). The incoming call can
be ended either by clicking the End button in the emulator or by clicking the Hang Up button in
the Emulator Control tab.

Simulating an incoming phone call through the Emulator Control tab (left), and an incoming phone call
appears on the Android emulator (right).
To simulate an SMS message, select the SMS option in the Emulator Control tab, provide the phone
number, write the message, and click the Send button, as shown in Figure(left). In the emulator, an
incoming SMS notification appears at the top (see Figure—right). We can simulate GPS coordinates
(longitude and latitude values) manually, via the GPX file or KML file through the Emulator Control tab.
Remember, only GPX 1.1 files are supported.

Simulating SMS via the Emulator Control tab (left), and incoming SMS notification displayed at the top
in the Android emulator (right)

The bottom pane of the DDMS is used to show the log of the processes on the selected device or AVD.
The pane is meant for performing debugging and tracing tasks. The LogCat tab shows all messages of the
device, including exceptions and those placed in the application to see the intermediate results. We can
also set up filters to watch filtered log information. The Console tab displays the messages related to the
starting of the activity.

Page 12
Mobile Application Development Unit-IV

Displaying and Fetching Information Using Dialogs and Fragments


A dialog is a smaller window that pops up to interact with the user. It can display important
messages and can even prompt for some data.
Once the interaction with the dialog is over, the dialog disappears, allowing the user to continue with the
application.
Fragments, as the name suggests, enable us to fragment or divide our Activities into encapsulated
reusable modules, each with its own user interface, making our application suitable to different screen
sizes. That is, depending on the available screen size, we can add or remove fragments in our application.
WHAT ARE DIALOGS?
We usually create a new activity or screen for interacting with users, but when we want only a little
information, or want to display an essential message, dialogs are preferred. Dialogs are also used to guide
users in providing requested information, confirming certain actions, and displaying warnings or error
messages. The following is an outline of different dialog window types provided by the Android SDK:
 Dialog—The basic class for all dialog types.
 AlertDialog—A dialog with one, two, or three Button controls.
 CharacterPickerDialog—A dialog that enables you to select an accented character associated
with a regular character source.
 DatePickerDialog—A dialog that enables you to set and select a date with a DatePicker control.
 ProgressDialog—A dialog that displays a ProgressBar control showing the progress of a
designated operation.
 TimePickerDialog—A dialog that enables you to set and select a time with a TimePicker control.
A dialog is created by creating an instance of the Dialog class. The Dialog class creates a dialog in the
form of a floating window containing messages and controls for user interaction. In Android, the dialogs
are called asynchronously; that is, the dialogs are displayed and the main thread that invokes the dialogs
returns and continues executing the rest of the application..
The following is a list of the Activity class dialog methods:
 showDialog()—Displays a dialog and creates a dialog if one does not exist. Each dialog has a
special dialog identifier that is passed to this method as a parameter.
 onCreateDialog()—The callback method that executes when the dialog is created for the first
time. It returns the dialog of the specified type.
 onPrepareDialog()—The callback method used for updating a dialog.
 dismissDialog()—Closes the dialog whose dialog identifier is supplied to this method. The dialog
can be displayed again through the showDialog() method.
 removeDialog()—The dismissDialog() method doesn’t destroy a dialog. The dismissed dialog
can be redisplayed from the cache. If we do not want to display a dialog, we can remove it from
the activity dialog pool by passing its dialog identifier to the removeDialog() method.

Page 13
Mobile Application Development Unit-IV

AlertDialog
An AlertDialog is a popular method of getting feedback from the user. This pop-up dialog remains there
until closed by the user and hence is used for showing critical messages that need immediate attention or
to get essential feedback before proceeding further.
The simplest way to construct an AlertDialog is to use the static inner class AlertDialog.Builder that
offers a series of methods to configure an AlertDialog.

AlertDialog.BuilderalertDialog = new AlertDialog.Builder(this);

Methods of the AlertDialog.Builder Subclass


The methods of the AlertDialog.Builder subclass that we can use to configure the AlertDialogbox are
 setTitle() and setIcon()—For specifying the text and icon to appear in the title bar of the dialog
box.
 setMessage()—For displaying a text message in the dialog box.
 setPositiveButton(), setNeutralButton(), and setNegativeButton()—For configuring the
following three buttons:
• Positive button—Represents the OK button.
• Negative button—Represents the Cancel button.
• Neutral button—Represents a button to perform a function other than OK or Cancel.
Through these three methods, we can set the three buttons to appear in the dialog and also define their
location in the dialog box. We can also define the captions and actions of these buttons.
Note:The AlertDialog can display up to three buttons, and all three buttons cause the Alert-dialog to be
dismissed.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayoutxmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="in.kvsw.alertdialog.MainActivity">
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/click_btn"
android:text="Click for Alert Dialog" />
</LinearLayout>
MainActivity.java file
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.view.View;
import android.app.AlertDialog;
import android.content.DialogInterface;

Page 14
Mobile Application Development Unit-IV

public class MainActivityextends AppCompatActivityimplements OnClickListener


{
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button b = (Button)this.findViewById(R.id.click_btn);
b.setOnClickListener(this);
}
@Override
public void onClick(View v)
{
AlertDialog.BuilderalertDialog = new AlertDialog.Builder(this);
alertDialog.setTitle("Alert window");
alertDialog.setIcon(R.drawable.ic_launcher);
alertDialog.setMessage("This is an alert");
alertDialog.setPositiveButton("OK", new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, intbuttonId)
{
return;
}
});
alertDialog.show();
}
@Override
public void onPointerCaptureChanged(booleanhasCapture)
{
}
}
OUTPUT:

Page 15
Mobile Application Development Unit-IV

SELECTING THE DATE AND TIME IN ONE APPLICATION


To see how the system date and time can be set in an application, let’s create a new Android
application and name it DateTimePickerApp. In this application, we use a TextView and
two Button controls. The TextView control displays the current system date and time, and the
two Button controls, Set Date and Set Time, are used to invoke the respective dialogs. When the Set
Date button is selected, the DatePickerDialog is invoked, and when the Set Time button is selected,
the TimePickerDialog is invoked.
So, let’s write the code shown in Listing 6.9 into the layout file activity_date_time_picker_app.xml to
define a TextView and two Button controls.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayoutxmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="in.kvsw.dateandtime.MainActivity">

<TextViewandroid:id="@+id/datetimevw"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<Button android:id="@+id/date_button"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Set Date" />
<Button android:id="@+id/time_button"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Set Time" />

</LinearLayout>

MainActivity.java

package in.kvsw.dateandtime;
import android.support.v7.app.AppCompatActivity;
import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
import android.widget.Button;
import java.util.Calendar;
import android.app.TimePickerDialog;
import android.app.DatePickerDialog;
import android.view.View.OnClickListener;
import android.view.View;
import android.widget.TimePicker;
import android.widget.DatePicker;

Page 16
Mobile Application Development Unit-IV

public class MainActivityextends AppCompatActivity


{
private TextViewdateTimeView;
private Calendar c;
private inth, m,yr,mon,dy;

@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
dateTimeView= (TextView) findViewById(R.id.datetimevw);
Button timeButton = (Button) findViewById(R.id.time_button);
Button dateButton = (Button) findViewById(R.id.date_button);
c = Calendar.getInstance();
h = c.get(Calendar.HOUR_OF_DAY);
m = c.get(Calendar.MINUTE);
yr= c.get(Calendar.YEAR);
mon= c.get(Calendar.MONTH);
dy= c.get(Calendar.DAY_OF_MONTH);
dateTimeView.setText("Current date is "+ (mon+1)+"-"+dy+"-"+yr+" and current
time is: "+h+":"+m);
dateButton.setOnClickListener(new OnClickListener()
{
public void onClick(View v)
{
new DatePickerDialog(MainActivity.this, dateListener,yr, mon, dy).show();
}
});
timeButton.setOnClickListener(new OnClickListener()
{
public void onClick(View v)
{
new TimePickerDialog(MainActivity.this, timeListener,h,m,true).show();
}
});
}

private DatePickerDialog.OnDateSetListenerdateListener= new


DatePickerDialog.OnDateSetListener() {
public void onDateSet(DatePicker view, intyear, intmonthOfYear, intdayOfMonth)
{
yr= year;
mon= monthOfYear;
dy= dayOfMonth;
dateTimeView.setText("Current date is "+ (mon+1)+"-"+dy+"-"+yr+" and current
time is: "+h+":"+m);
}
};

Page 17
Mobile Application Development Unit-IV

private TimePickerDialog.OnTimeSetListenertimeListener= new


TimePickerDialog.OnTimeSetListener()
{
public void onTimeSet(TimePicker view, inthour, intminute)
{
h = hour;
m = minute;
dateTimeView.setText("Current date is "+ (mon+1)+"-"+dy+"-"+yr+" and current
time is:"+h+":"+m);
}
};
}
OUTPUT:

Android 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.

Android fragment lifecycle is affected by activity lifecycle because fragments are included in activity.

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.

Android Fragment Lifecycle

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

Page 18
Mobile Application Development Unit-IV

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.

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


ViewGroup, Bundle)

4) onActivityCreated(Bundle) It is invoked after the completion of onCreate()


method.

5) onViewStateRestored(Bundle) It provides information to the fragment that all

Page 19
Mobile Application Development Unit-IV

the saved state of fragment view hierarchy has


been restored.

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.

11) onDestroy() allows the fragment to do final clean up of


fragment state.

12) onDetach() It is called immediately prior to the fragment no


longer being associated with its activity.
Android Fragment Example
Let's have a look at the simple example of android fragment.
activity_main.xml
File: activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayoutxmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="in.kvsw.fragments.MainActivity">
<fragment
android:id="@+id/fragment1"
android:name="in.kvsw.fragments.Fragments1"
android:layout_width="0px"
android:layout_height="match_parent"
android:layout_weight="1"
/>
<fragment
android:id="@+id/fragment2"
android:name="in.kvsw.fragments.Fragment2"
android:layout_width="0px"
android:layout_height="match_parent"
android:layout_weight="1"
/>
</LinearLayout>
File: fragment_fragment1.xml
<?xml version="1.0" encoding="utf-8"?>
<FrameLayoutxmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#F5F5DC">
<!-- TODO: Update blank fragment layout -->
<TextView
Page 20
Mobile Application Development Unit-IV

android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="hello_blank_fragment"/>
</FrameLayout>
File: fragment_fragment2.xml
<?xml version="1.0" encoding="utf-8"?>
<FrameLayoutxmlns:android="http://schemas.android.com/apk/res/android"
android:background="#F0FFFF"
android:layout_width="match_parent"
android:layout_height="match_parent">
<!-- TODO: Update blank fragment layout -->
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="hello_blank_fragment"/>

</FrameLayout>

MainActivity class
File: MainActivity.java
packagein.kvsw.fragments;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;

public class MainActivityextends AppCompatActivity


{

@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}

File: Fragments1.java
package in.kvsw.fragments;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

public class Fragments1 extends Fragment


{

@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
}

Page 21
Mobile Application Development Unit-IV

@Override
public View onCreateView(LayoutInflaterinflater, ViewGroup container,
Bundle savedInstanceState)
{
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_fragment1, container, false);
}
}

File: Fragment2.java
package in.kvsw.fragments;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class Fragment2 extends Fragment
{
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
}
@Override
public View onCreateView(LayoutInflaterinflater, ViewGroup container,
Bundle savedInstanceState)
{
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_fragment2, container, false);
}

Output:

Page 22

You might also like