0% found this document useful (0 votes)
219 views41 pages

Unit-4 Using Selection Widgets and Debugging

The document discusses using selection widgets like ListView and Spinner in Android. It explains how to populate a ListView from string resources and an adapter. It also explains how to populate a Spinner from string resources and set an item click listener.

Uploaded by

krupa522
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
219 views41 pages

Unit-4 Using Selection Widgets and Debugging

The document discusses using selection widgets like ListView and Spinner in Android. It explains how to populate a ListView from string resources and an adapter. It also explains how to populate a Spinner from string resources and set an item click listener.

Uploaded by

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

Unit-4

Unit-4
Using Selection widgets and Debugging
Using ListView:
 ListView is used to display a list of vertically scrolling items, allowing users to select one or more
of them.

 Listview can be created with the tag called <ListView>

 The following syntax can be used for creating the listview:

Ex: <ListView

android:layout_width=“match_parent”

android:layout_height=“match_parent”

android:entries=“@array/fruits”

android:choiceMode=“singleChoice”

android:drawSelectionOnTop=“false”

android:transcriptMode=“normal”/>

 The following attributes are used for ListView Control

Attribute Description

Entries Used to refer an array resource for displaying options in the ListView
choiceMode Used to define the number of items that are selectable from the ListView
1) none: Doesn’t allow selection of any option from the ListView
2) singleChoice: Allows selection of a single option from the ListView
3) multipleChoice: Allows selection of multiple options from the ListView

drawSelectorOnTop When set to “true” ,the selector is drawn over the selected item.

transcriptMode Allows the list to automatically scroll to the bottom.


1) disabled- disables the transcript mode
2) normal- allows automatically scrolls to the bottom when a new item added
3) alwaysScroll- The ListView always automatically scrolls to the bottom
Creating ListView with an Activity Base class:

Dept of CSE, C.B.I.T,PDTR Page 1


Unit-4

• Whether we are creating a ListView by extending the Activity class or the ListActivity class, the
ListView can be populated by one of the following two methods:

1) By ListView through string resource

2) By ListView through Adapter

Populating ListView through String resource:

ListView is populated through string resources to display a list of items for the user to select from.

Open the string resource file /res/values/string.xml and add a string array structure called Fruits that list
various fruits we want to display via the ListView control.

<resources>

<string name=“app_name”>ListViewApp</string>

<string-array name=“fruits”>

<item>Apple</item>

<item>Mango</item>

<item>Banana</item> </string-array>

</resources>

• After we define array, the next step is to define xml file.

activity_list_view_app.xml

<LinearLayout

Xmlns:android=http://schemas.android.com/apk/res/android

android:layout_width=“match_parent”

android:layout_height=“match_parent”

android:Orientation=“vertical”>

<ListView

android:id=“@+id/frtlist”

android:layout_width=“match_parent”

android:layout_height=“match_parent”

Dept of CSE, C.B.I.T,PDTR Page 2


Unit-4

android:entries=“@array/fruits”/>

<TextView

android:layout_width=“match_parent”

android:layout_height=“wrap_content”

android:id=“@+id/txtv”/>

</LinearLayout>

ListViewAppActivity.java

import android.app.Activity;

import android.os.Bundle;

import android.view.View;

import android.widget.TextView;

import android.ListView;

import android.widget.AdapterView;

import android.widget.AdapterView.OnItemClickListener;

public class ListViewAppActivity extends Activity

@Override

public void onCreate(Bundle savedInstanceState)

Super.onCreate(savedInstanceState);

setContentView(R.layout.activity_list_view_app);

final String[] fruitsArray=getResources().getStringArray(R.array.fruits);

final TextView selectdOpt=(TextView)findViewById(R.id.txtv);

ListView fruitsList=(ListView) findViewById(R.id.frtlist);

fruitsList.setOnItemClickListener(new OnItemClickListener()

Dept of CSE, C.B.I.T,PDTR Page 3


Unit-4

@Override

public void onItemClick(AdapterView<?> parent, View v, int position, long id)

selectedOpt.setText(“you have selected”+fruitsArray[position]);

});

By ListView through Adapter:

The Adapters serve two purposes.

 First they provide the data source for selection widget

 Second they convert individual elements of data into specific Views to be displayed inside the
selection widget.

 Android provides many basic adapters such as ListAdapter,ArrayAdapter, and CursorAdapter.

Populating ListView through the ArrayAdapter:

 The ArrayAdapter is one of the adapters provided by Android that provides data sources to
selection widgets.

 An ArrayAdapter can be created through string resources.

activity_list_view_app.xml

<LinearLayout

Xmlns:android=http://schemas.android.com/apk/res/android

android:layout_width=“match_parent”

android:layout_height=“match_parent”

Dept of CSE, C.B.I.T,PDTR Page 4


Unit-4

android:Orientation=“vertical”>

<ListView

android:id=“@+id/frtlist”

android:layout_width=“match_parent”

android:layout_height=“match_parent”/>

<TextView

android:layout_width=“match_parent”

android:layout_height=“wrap_content”

android:id=“@+id/txtv”/>

</LinearLayout>

ListViewAppActivity.java

import android.app.Activity;

import android.os.Bundle;

import android.view.View;

import android.widget.TextView;

import android.ListView;

import android.widget.AdapterView;

import android.widget.ArrayAdapter;

import android.widget.AdapterView.OnItemClickListener;

public class ListViewAppActivity extends Activity

@Override

public void onCreate(Bundle savedInstanceState)

Super.onCreate(savedInstanceState);

setContentView(R.layout.activity_list_view_app);
Dept of CSE, C.B.I.T,PDTR Page 5
Unit-4

final String[] fruits={“Apple”,”Mango”,”Banana”,”Orange”,”Grapes”};

final TextView selectdOpt=(TextView)findViewById(R.id.txtv);

ListView fruitlist=(ListView)findViewById(R.id.frtlist)

final ArrayAdapter<String> arrayadpt=new ArrayAdapter<String> (this,


android.R.layout.simple_list_item_1, fruits);

fruitlist.setAdapter(arrayAdpt);

fruitlist.setOnItemClickListener(new onItemClickListener()

@Override

public void onItemClick(AdapterView<?>parent, View v, int position, long id)

selectedOpt.setText(“You have selected”+fruits[position]);

});

Using Spinner Control:

Dept of CSE, C.B.I.T,PDTR Page 6


Unit-4

 The spinner is akin to drop-down list that display a list of items and allows the user to select the
desired item.

 To populate the spinner control we use 2 methods.

1) Through string resources

2) Through ArrayAdapter

The following shows the syntax for creating spinner control:

<Spinner

android:id=@+id/sp

android:layout_width=“match_parent”

Android:layout_height=“match_parent”

android:prompt=“@string/choose_msg”

android:entries=“@array/fruits”/>

android:prompt:- attribute is used for displaying the text what need to display defaulty.

android:entries:-used for adding the list of items to the spinner

1) Through string resources:

strings.xml

<resources>

<string name=“app_name”>SpinnerApp</string>

<string name=“choose_msg”> Choose a fruit</string>

</resources>

Dept of CSE, C.B.I.T,PDTR Page 7


Unit-4

arrays.xml:

<resources>

<string-array name=“fruits”>

<item>Apple</item>

<item>Banana</item>

<item>Orange</item>

<item>Grapes</item>

</string-array>

</resources>

activity_spinner_app.xml

<LinearLayout

Xmlns:android=http://schemas.android.com/apk/res/android

android:layout_width=“match_parent”

android:layout_height=“match_parent”>

<Spinner

android:id=“@+id/sp”

android:layout_width=“match_parent”

android:layout_height=“wrap_content”

android:prompt=“@string/choose_msg”

android:entries=“@array/fruits”/>

<TextView

android:id=“@+id/selectedopt”

android:layout_width=“match_parent”

android:layout_height=“wrap_content”/>

</LinearLayout>

Dept of CSE, C.B.I.T,PDTR Page 8


Unit-4

SpinnerAppActivity.java

import android.app.Activity;

import android.os.Bundle;

import android.view.View;

import android.widget.TextView;

import android.widget.Spinner;

import android.widget.AdapterView;

import android.widget.AdapterView.OnItemSelectedListener;

public class SpinnerAppActvity extends Activity

@Override

public onCreate (Bundle savedInstanceState)

Super.onCreate(savedInstanceState);

setContentView(R.layout.activity_spinner_app);

final TextView tv=(TextView)findViewById(R.id.Selectedop);

final Spinner spin=(Spinner)findViewById(R.id.sp);

final String[ ] fruitsarray=getResources().getStringArray(R.array.fruits);

Spin.setOnItemSelectedListener(new OnItemSelectedListener()

Public void onItemSelected(AdapterView<?>prent, View v, int position, long id)

tv.setText(“You have selected” +fruitsArray[position]);

Public void onNothingSelected(AdapterView<?>parent)

{
Dept of CSE, C.B.I.T,PDTR Page 9
Unit-4

tv.setText(“ “);

});

2) Through ArrayAdapter:
activity_spinner_app.xml

<LinearLayout

Xmlns:android=http://schemas.android.com/apk/res/android

android:layout_width=“match_parent”

android:layout_height=“match_parent”>

<Spinner

android:id=“@+id/sp”

android:layout_width=“match_parent”

android:layout_height=“wrap_content”

android:prompt=“@string/choose_msg”/>

<TextView

android:id=“@+id/selectedopt”

android:layout_width=“match_parent”

android:layout_height=“wrap_content”/>

</LinearLayout>

SpinnerAppActivity.java

import android.app.Activity;

import android.os.Bundle;

Dept of CSE, C.B.I.T,PDTR Page 10


Unit-4

import android.view.View;

import android.widget.TextView;

import android.widget.Spinner;

import android.widget.ArrayAdapter;

import android.widget.AdapterView;

import android.widget.AdapterView.OnItemSelectedListener;

Public class SpinnerAppActvity extends Activity

@Override

Public onCreate (Bundle savedInstanceState)

Super.onCreate(savedInstanceState);

setContentView(R.layout.activity_spinner_app);

final TextView tv=(TextView)findViewById(R.id.Selectedop);

final String [ ] fruits={“Apple”, “Banana”,”Orange”, “Grapes”,”Mango”};

final Spinner spin=(Spinner)findViewById(R.id.sp);

ArrayAdapter<String> arradpt=new ArrayAdapter<String> (this,


android.R.layout.simple_spinner_item, fruits);

Spin.setAdapter(arrayAdpt);

Spin.setOnItemSelectedListener(new OnItemSelectedListener()

Public void onItemSelected(AdapterView<?>prent, View v, int position, long id)

tv.setText(“You have selected” +fruitsArray[position]);

Public void onNothingSelected(AdapterView<?>parent)

Dept of CSE, C.B.I.T,PDTR Page 11


Unit-4

tv.setText(“ “);

});

AutoCompleteTextView:

 The AutocompleteTextView control is an EditText control with auto-complete functionality.

 As the user types, suggestions based on the entered characters appear.

 To implement the auto complete facility, we create an ArrayAdapter and set it to display items
or suggestions from data source.

 AutocompleteTextView can be created with <AutoCompleteTextView>. It’s a standalone tag.

Activity_auto_complete_app.xml

<LinearLayout

Xmlns:android=http://schemas.android.com/apk/res/android

android:layout_width=“match_parent”

android:layout_height=“match_parent”>

<TextView

android:text=“Enter Product Name:”

android:layout_width=“match_parent”

android:layout_height=“wrap_content”/>

<AutoCompleteTextView

android:layout_width=“match_parent”

android:layout_height=“wrap_content”

Dept of CSE, C.B.I.T,PDTR Page 12


Unit-4

Android:id=“@+id/actv”/>

</LinearLayout>

AutoCompleteAppActivity.java

import android.app.Activity;

import android.os.Bundle;

import android.view.View;

import android.widget.ArrayAdapter;

import android.widget.AutoCompleteTextView;

public class AutoCompleteAppActivity extends Activity

@Override

Public onCreate (Bundle savedInstanceState)

String [ ] products={“Camera”, “Mobile”, ”Laptop”, “Headphone”, ”bluetooth”};

Super.onCreate(savedInstanceState);

setContentView(R.layout.activity_auto_complete_app);

ArrayAdapter<String> arradpt=new ArrayAdapter<String> (this,


android.R.layout.simple_dropdown_item, products);

AutoCompleteTextView prduct=(AutoCompleteTextView)findViewById(R.id.actv);

prduct.setThreshold(2);

prduct.setAdapter(arradpt);

setThreshold(): method is used to indicate the minimum number of characters that a user must enter
before the suggestions are displayed.

Dept of CSE, C.B.I.T,PDTR Page 13


Unit-4

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 GridView control in the XML layout, and then bind the
data that we want to be displayed to it using the ArrayAdapter.

 Gridview Can be create with the tag <GridView>

 The following are the attributes supported for Gridview.

1) android:columnWidth

This specifies the fixed width for each column. This could be in px, dp, sp, in, or mm.

2) android:gravity

Specifies the gravity within each cell. Possible values are top, bottom, left, right, center, center_vertical,
center_horizontal etc.

3) android:horizontalSpacing and android:verticalSpacing:

Defines the amount of spacing between items in the grid. This could be in px, dp, sp, in, or mm.

4) android:numColumns

Defines how many columns to show. May be an integer value, such as "100“. Or we can give the value as
auto_fit can gives the no of columns based on available space.

Ex: activity_grid_view_app.xml

<LinearLayout

Dept of CSE, C.B.I.T,PDTR Page 14


Unit-4

Xmlns:android=http://schemas.android.com/apk/res/android

android:layout_width=“match_parent”

android:layout_height=“match_parent”>

<TextView

android:id=“@+id/tv”

android:text=“Select a fruit:”

android:layout_width=“match_parent”

android:layout_height=“wrap_content”/>

<GridView

android:id=“@+id/grid”

android:layout_width=“match_parent”

android:layout_height=“match_parent”

android:verticalSpacing=“2dip”

android:horizontalSpacing=“5dip”

android:numColumns=“auto_fit”

android:gravity=“center”/>

</LinearLayout>

GridViewAppActvity.java

import android.app.Activity;

import android.os.Bundle;

import android.view.View;

import android.widget.TextView;

import android.widget.GridView;

import android.widget.ArrayAdapter;

import android.widget.AdapterView;

public class GridViewAppActivity extends Activity


Dept of CSE, C.B.I.T,PDTR Page 15
Unit-4

String [ ] fruits={“Apple”, “Banana”,”Orange”, “Grapes”,”Mango”,”Pineapple”, ”Strawberry”,


“papaya”,”pomogranade”,”watermelon”,”plum”,”cherry”,”kiwi”};

@Override

Public onCreate (Bundle savedInstanceState)

Super.onCreate(savedInstanceState);

setContentView(R.layout.activity_grid_view_app);

final TextView selectedop=(TextView)findViewById(R.id.tv);

GridView g=(GridView)findViewById(R.id.grid);

ArrayAdapter<String> arradpt=new ArrayAdapter<String> (this,android.R.layout.simple_list_item_1,


fruits);

g.setAdapter(arrayAdpt);

g.setOnItemClickListener(this);

public void onItemClick(AdapterView<?>prent, View v, int position, long id)

selectedop.setText(“You have selected” +fruitsArray[position]);

Public void onNothingSelected(AdapterView<?>parent)

selectedop.setText(“ “);

Displaying Images in GridView:

 To display content in GridView we use Adapters, which provide the content to display to the
controls.

Dept of CSE, C.B.I.T,PDTR Page 16


Unit-4

 For displaying through GridView first we need to add images to the res/drawable folder.
Assume we have added 4 images called one.jpeg,two.jpeg,three.jpeg,four.jpeg . Lets create
the GridIamgeApp.

activity_grid_image_app.xml

<LinearLayout

Xmlns:android=http://schemas.android.com/apk/res/android

android:layout_width=“match_parent”

android:layout_height=“match_parent”

android:Orientation=“vertical”>

<TextView

android:id=“@+id/tv”

android:text=“Select an image:”

android:layout_width=“match_parent”

android:layout_height=“wrap_content”/>

<GridView

android: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=“100dip”

android:gravity=“center”/>

</LinearLayout>

GridImageAppActivity.java

Dept of CSE, C.B.I.T,PDTR Page 17


Unit-4

import android.app.Activity;

import android.os.Bundle;

import android.view.View;

import android.widget.TextView;

import android.widget.GridView;

import android.widget.ImageView;

import android.content.Context; Context is used for creating new ImageView

import android.widget.BaseAdapter; BaseAdapter is used for creating our own adapter

import android.widget.AdapterView;

import android.view.ViewGroup;

public class GridImageAppActivity extends Activity implements AdapterView.OnItemClickListener

@Override

Public onCreate (Bundle savedInstanceState)

Super.onCreate(savedInstanceState);

setContentView(R.layout.activity_grid_image_app);

TextView selectedop=(TextView)findViewById(R.id.tv);

GridView g=(GridView)findViewById(R.id.grid);

g.setAdapter(new ImageAdapter(this));

g.setOnItemClickListener(this);

public void onItemClick(AdapterView<?>prent, View v, int position, long id)

int p=position+1;

selectedop.setText(“You have selected image number” +p);


Dept of CSE, C.B.I.T,PDTR Page 18
Unit-4

public class ImageAdapter extends BaseAdapter

private Context contxt;

Interger [ ] images={ R.drawable.one, R.drawable.two, R.drawable.three, R.drawable.four};

Public ImageAdapter(Context c)

Contxt=c;

public int getCount()

return images.length;

public Object getItem(int position)

return position;

public long getItemId(int position)

return position;

public View getView(int position, View convertView, ViewGroup parent )

ImageView iv=new ImageView(contxt);

iv.setImageResource(images[position]);

iv.setLayoutParams(new GridView.LayoutParams(100,120));
Dept of CSE, C.B.I.T,PDTR Page 19
Unit-4

return imageView;

 The height and width of the image are set by setting the GridView.LayoutParams()
method.

Creating an Image Gallery Using the ViewPager Control:

 ViewPager control can be used for displaying data which may be text , image etc., in the form of
pages with horizontal swiping behavior i.e., flipped from left to right.

 ViewPager can be defined with android.support.v4.view.ViewPager

 The ViewPager needs a data adapter for define and loading the data for each page.

 That data adapter is PagerAdapter (android.support.v4.View.PagerAdapter) class.

 While implementing the PagerAdapter we must override the following methods:

1)instantiateItem(View container, int position):

Used for creating and instantiating the page and adding it to the container

Container: Represents the container in which the page has to be displayed

Position: Represents the position of the page to be instantiated.

2)destroyItem(): used for removing the page from container of specified position.

3)isViewFromObject(): Determines whether the specified page is associated with specified with
specified key object.

4)getCount(): Defines the size of the paging range , that is the count of the number of the pages.

Ex: Image Gallery App

activity_view_pager_app.xml

<LinearLayout

Xmlns:android=http://schemas.android.com/apk/res/android

Dept of CSE, C.B.I.T,PDTR Page 20


Unit-4

android:layout_width=“match_parent”

android:layout_height=“match_parent”

android:Orientation=“vertical”>

<TextView

android:id=“@+id/tv”

android:text=“Image Gallery”

android:layout_width=“match_parent”

android:layout_height=“wrap_content”/>

<android.support.v4.ViewPager>

android:id=“@+id/viewpager”

android:layout_width=“match_parent”

android:layout_height=“100dip”/>

</LinearLayout>

ViewPagerAppActivity.java

import android.os.Bundle;

import android.view.View;

import android.app.Activity;

import android.widget.ImageView;

import android.widget.TextView;

import android.support.v4.view.ViewPager;

import android.support.v4.view.PagerAdapter;

import android.support.v4.view.ViewPager.SimpleOnPageChangeListener;

public class ViewPagerAppActivity extends Activity

@Override

Dept of CSE, C.B.I.T,PDTR Page 21


Unit-4

Public onCreate (Bundle savedInstanceState)

Super.onCreate(savedInstanceState);

setContentView(R.layout.activity_view_pager_app);

TextView selectedop=(TextView)findViewById(R.id.tv);

ViewPager vpg=(ViewPager)findViewById(R.id.viewpager);

vpg.setAdapter(new ImageAdapter( ));

vpg.setOnPageChangeListener(new PageListener( ));

public class ImageAdapter extends BaseAdapter

private Context contxt;

Interger [ ] images={ R.drawable.one, R.drawable.two, R.drawable.three, R.drawable.four};

public Object instantiateItem(View Container, int position)

ImageView iv=new ImageView(ViewPagerAppActivity.this);

iv.setImageResource(images[position]);

((ViewPager) container).addView(view,0);

return view;

@Override

Public int getCount()

return imges.length;

@Override
Dept of CSE, C.B.I.T,PDTR Page 22
Unit-4

public void destroyItem(View arg0, int arg1, object arg2)

((ViewPager) arg0).removeView((View) arg2);

@Override

public boolean isViewFromObject(View arg0, Object arg1)

return arg0 ==((View) arg1);

private class PageListener extends SimpleOnPageChangeLsitener

public void OnPageSelected(int position)

Selectedop.setText(“You have selected the page number”+position);

Dept of CSE, C.B.I.T,PDTR Page 23


Unit-4

Using the Debugging Tool: Dalvik Debug Monitor Servie(DDMS)

 The DDMS is a powerful debugging tool that is downloaded as part of androidSDK.

 DDMS can run by selecting Windows open Perspective DDMS

 When we run DDMS, it automatically connects to the attached android device or any running
emulator.

 DDMS helps with following tasks

a. Finding bugs in applications running on emulator

b. Services like incoming calls , SMS, and location data spoofing

c. Generates LogCat, which displays the log messages about the state of the application.

 In the upper left pane of DDMS window, we see a Devices tab that display the list of devices
connected.

 On the right pane we find following tabs:

1) Threads: Displays information about the threads within each process

2) Heap: Displays heap information of the process.

3) Allocation Tracker: Tracks the objects allocated to an application.

4) Network Statistics: Helps us in getting information regarding network usage of our application

5) File Explorer: Displays the file system on the device.

Debugging Applications:

 Debugging is the process of removing errors.

 Select Run Debug android application.

 When the application switches to Debug perspective on the screen you will see options like
callback stack, console, code view, and variables.

 The following panes are visible by default in Debug perspective:

1)Debug Pane: The debug pane displays debug session information in a tree hierarchy.

 The following buttons appear at the top of this pane:


Dept of CSE, C.B.I.T,PDTR Page 24
Unit-4

i. Resume: Resumes execution of currently suspended debugging session.

ii. Suspend: Pauses the selected debugging session.

iii. Terminate: Ends the selected debugging session.

iv. Disconnect: Disconnects the debugger from the selected debug target.

2) Expressions Pane: This pane is used for compute expressions with different variables of the
application.

 The expression pane is not visible by default. To open it click on

Window Show View Expressions

Note: The variables what are used in the expression must exists in the application.

3) Breakpoints Pane: The breakpoints pane displays all the inserted breakpoints in the application.

 Breakpoints are used to temporarily pause execution of the application.

 This pane helps in enabling , disabling, skipping and removing breakpoints, and also helps in
suspending the breakpoint on specific condition.

4) Variables Pane: The Variables Pane displays values of the variables associated with the stack frame
selected in the Debug pane.

What are Dialogs:


 Dialogs are small screens created for interacting with users.

 Dialogs are used for display small information and also used for guide the users.

 The following different dialog window types provided by Android:

i. Dialog: The basic class for all dialog types.

ii. AlertDialog: A Dialog with one, two, three button controls.

iii. CharacterPickerDialog: A dialog that enables you to select an accented character associated
with a regular character source.

iv. DatePickerDialog: A dialog that enables you to set and select a date with a DatePicker control.

v. ProgressDialog: A dialog that displays a ProgressBar control showing the progress of a


designated operation.

Dept of CSE, C.B.I.T,PDTR Page 25


Unit-4

vi. TimePickerDialog: A dialog that enables you set and select a time with a TimePicker Control.

Alert Diaolug:

 Alert Dialog can be constructed through AlertDialog.Builder subclass .

 This class consist of following methods

1) setTitle(): Used for setting the title of Dialog Box

2) setIcon(): Used for setting icon to be appear on bar of dialog box.

3) setMessage(): Used for adding the message which you want to display on the dialog box.

4) setPositiveButton(): Represents the OK Button

5) setNegativeButton(): Represents Cancel Button

6) SetNeutralButton(): Represents the button to perform other than ok or cancel

Ex: activity_alert_dialog_app.xml

<LinearLayout

xmlns:android=http://schemas.android.com/apk/res/android

android:layout_width=“match_parent”

android:layout_height=“match_parent”

android:Orientation=“vertical”>

<Button

android:id=“@+id/clck_btn”

android:text=“Click for alert Dialog”

android:layout_width=“match_parent”

android:layout_height=“wrap_content”/>

</LinearLayout>

AlertDialogAppActivity.java

import android.os.Bundle;

import android.view.View;

Dept of CSE, C.B.I.T,PDTR Page 26


Unit-4

import android.app.Activity;

import android.widget.Button;

import android.view.View.OnClickListener;

import android.app.AlertDialog;

import android.content.DialogInterface;

public class AlertDialogAppActivity extends Activity

@Override

Public onCreate (Bundle savedInstanceState)

Super.onCreate(savedInstanceState);

setContentView(R.layout.activity_alert_dialog_app);

Button b= (Button)this.FindViewById(R.id.clck_btn)

b.setOnClickListener(this);

@Override

public void onClick(View v)

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

ad.setTitle(“Alert Window”);

ad.setIcon(“R.drawable.one”);

ad.setMessage(“This is alert”);

ad.setPositiveButton(“OK”, new DialogInterface.OnClickListener()

public void onClick(DialogInterface dialog,int buttonId)

{
Dept of CSE, C.B.I.T,PDTR Page 27
Unit-4

return;

});

ad.show();

DatePickerDialog:

 DatePickerDialog is used to see and modify the date.

 We supply day , month ,year values to its constructor

 To initialize the current date to the dialog, we use a Calendar instance.

Ex: activity_date_picker_app.xml

<LinearLayout

xmlns:android=http://schemas.android.com/apk/res/android

android:layout_width=“match_parent”

android:layout_height=“match_parent”

android:Orientation=“vertical”>

<Button

android:id=“@+id/dt_btn”

android:text=“set Date”

android:layout_width=“match_parent”

android:layout_height=“wrap_content”/>

<TextView

android:id=“@+id/dtvw”

android:layout_width=“match_parent”

android:layout_height=“wrap_content”/>

</LinearLayout>
Dept of CSE, C.B.I.T,PDTR Page 28
Unit-4

DatePickerAppActivity.java

import android.os.Bundle;

import android.view.View;

import android.app.Activity;

import android.widget.Button;

import android.widget.TextView;

import android.view.View.OnClickListener;

import android.app.DateDialog;

import android.util.Calendar;

import android.view.View;

import androi.widget.DatePicker;

public class DatePickerAppActivity extends Activity

private int yr,mon,dy;

@Override

Public onCreate (Bundle savedInstanceState)

Super.onCreate(savedInstanceState);

setContentView(R.layout.activity_date_picker_app);

Button db= (Button)this.FindViewById(R.id.clck_btn);

TextView tv=(TextView)findViewById(R.id.dtvw);

final Calendar c=Calendar.getInstance();

yr=c.get(Calendar.YEAR);

mon=c.get(Calendar.MONTH);

dy=c.get(Calendar.DAY_OF_MONTH);

tv.setText(“Current date is:”+(mon+1)+”-”+dy+”-”+yr);


Dept of CSE, C.B.I.T,PDTR Page 29
Unit-4

db.setOnClickListener(new OnClickListener()

public void onClick(View v)

new DatePickerDialog(DatePickerAppActivity.this,dateListener,yr,mon,dy).show();

});

private DatePickerDialog.OnDateSetListener dl=new DatePickerDialog.OnDateSetListener()

public void onDtaeSet(DatePicker view,int year,int month,int day)

yr=year;

mon=month;

dy=day;

tv.setText(“Current date is:” +(mon+1)+”-”+dy+”-”+yr);

}; }

Dept of CSE, C.B.I.T,PDTR Page 30


Unit-4

TimePickerDialog:
 TimePickerDialog allows us to set or select time through the built-in android TimePicker View.

 We can set the values of hour and minutes.

 The dialog provides a callback listener onTimeChangedListener or OnTimeSetListener ,which


tells us when a time is changed or set by the user.

Ex: activity_time_picker_app.xml

<LinearLayout

xmlns:android=http://schemas.android.com/apk/res/android

android:layout_width=“match_parent”

android:layout_height=“match_parent”

android:Orientation=“vertical”>

<Button

android:id=“@+id/tm_btn”

android:text=“set the Time”

android:layout_width=“match_parent”

android:layout_height=“wrap_content”/>

<TextView

android:id=“@+id/tmvw”

android:layout_width=“match_parent”

android:layout_height=“wrap_content”/></LinearLayout>

TimePickerAppActivity.java

import android.os.Bundle;

import android.view.View;

import android.app.Activity;

import android.widget.Button;
Dept of CSE, C.B.I.T,PDTR Page 31
Unit-4

import android.widget.TextView;

import android.view.View.OnClickListener;

import java.util.Calendar;

import android.util.Calendar;

import android.view.View;

import androi.widget.TimePicker;

public class TimePickerAppActivity extends Activity

private int h,m;

@Override

Public onCreate (Bundle savedInstanceState)

Super.onCreate(savedInstanceState);

setContentView(R.layout.activity_time_picker_app);

Button tb= (Button)this.FindViewById(R.id.clck_btn);

TextView tv=(TextView)findViewById(R.id.dtvw);

final Calendar c=Calendar.getInstance();

h=c.get(Calendar.HOUR_OF_DAY);

m=c.get(Calendar.MINUTE);

tv.setText(“Current time is:”+h+”:”+m);

tb.setOnClickListener(new OnClickListener()

public void onClick(View v)

new TimePickerDialog(TimeIckerAppActivity.this, timeListener,h,m,true).show();

}
Dept of CSE, C.B.I.T,PDTR Page 32
Unit-4

});

private TimePickerDialog.OnTimeSetListener tl=new TimePickerDialog.OnTimeSetListener()

public void onTimeSet(TimePicker view,int hour,int min)

h=hour;

m=min;

tv.setText(“Current time is:”+h+”:”+m);

}; }

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.

Activity_date_time_picker_app.xml

<LinearLayout

xmlns:android=http://schemas.android.com/apk/res/android

android:layout_width=“match_parent”

android:layout_height=“match_parent”

android:Orientation=“vertical”>

<Button

android:id=“@+id/tm_btn”

android:text=“set the Time”

android:layout_width=“match_parent”

android:layout_height=“wrap_content”/>

<Button

Dept of CSE, C.B.I.T,PDTR Page 33


Unit-4

android:id=“@+id/dt_btn”

android:text=“set the Date”

android:layout_width=“match_parent”

android:layout_height=“wrap_content”/>

<TextView

android:id=“@+id/dtmvw”

android:layout_width=“match_parent”

android:layout_height=“wrap_content”/></LinearLayout>

DateTimePickerAppActivity.java

import android.os.Bundle;

import android.view.View;

import android.app.Activity;

import android.widget.Button;

import android.widget.TextView;

import android.view.View.OnClickListener;

import java.util.Calendar;

import android.util.Calendar;

import android.view.View;

import androi.widget.TimePicker;

import androi.widget.DatePicker;

public class DateTimePickerAppActivity extends Activity

private int h,m,yr,mon,dy;

Dept of CSE, C.B.I.T,PDTR Page 34


Unit-4

@Override

Public onCreate (Bundle savedInstanceState)

Super.onCreate(savedInstanceState);

setContentView(R.layout.activity_date_time_picker_app);

Button tb= (Button)this.FindViewById(R.id.tb_btn);

Button db= (Button)this.FindViewById(R.id.dt_btn);

TextView dtv=(TextView)findViewById(R.id.dtmvw);

final Calendar 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);

dtv.setText(“Current time is:”+h+”:”+m “and current date is:”+(mon+1)+”-“+dy+”-“+yr );

db.setOnClickListener(new OnClickListener()

public void onClick(View v)

new DatePickerDialog(DatePickerAppActivity.this,dateListener,yr,mon,dy).show();

});

tb.setOnClickListener(new OnClickListener()

public void onClick(View v)

{
Dept of CSE, C.B.I.T,PDTR Page 35
Unit-4

new TimePickerDialog(TimeIckerAppActivity.this, timeListener,h,m,true).show();

});

private DatePickerDialog.OnDateSetListener dl=new DatePickerDialog.OnDateSetListener()

public void onDtaeSet(DatePicker view,int year,int month,int day)

yr=year;

mon=month;

dy=day;

dtv.setText(“Current date is:” +(mon+1)+”-”+dy+”-”+yr);

};

private TimePickerDialog.OnTimeSetListener tl=new TimePickerDialog.OnTimeSetListener()

public void onTimeSet(TimePicker view,int hour,int min)

h=hour;

m=min;

dtv.setText(“Current time is:”+h+”:”+m);

};

Dept of CSE, C.B.I.T,PDTR Page 36


Unit-4

Fragments:
 A Fragment is a combination of an activity and a layout. It contains a set of views that makeup
an independent user interface.

 Fragments can be dynamically adjust to various views like landscape , potrait and even can
based on target device.

 A fragment is like a sub activity with its own lifecycle and view hierarchy.

 To create a fragment, we need to extend the Fragment class.

Life Cycle of a Fragment:

The life cycle of a fragment includes several callback methods. Those are:

1) onAttach(): Called when the fragment is attached to the activity.

2) onCreate(): Called when the fragment is going to create.

3) onCreateView(): called to create the view for the fragment.

4) onActivityCreated(): called when the actvity’s onCreate() method is returned.

5) onStart(): called when the fragment is visible to the user.

6) onResume(): called when the fragment is visible and is running.

7) onPause(): called when the fragment is visible but does not have focus.
Dept of CSE, C.B.I.T,PDTR Page 37
Unit-4

8) onStop(): called when the fragment is not visible.

9) onDestroyView()Fragment view will destroy after call this method.


10) onDestroy(): called when the fragment is no longer in use.

11) onDetach(): called when the fragment is detached from the activity.

Creating Fragments with java Code:

 There are two ways for creating Fragments one is by using <fragment> tag in the layout file of
the application but this can be static.

 For creating, adding and replacing fragments dynamically we use FragmentManager in activity
(java)file.

 FragmentManager is used to manage fragments in an activity. It provides various methods to


access fragments.

 It also enables us to perform FragmentTransaction required to add , remove and replace


fragments.

 To access FragmentManager the method we need to use is getFragmentManager() as shown


below:

FragmentManager fm=getFragmentManager();

 To perform Fragment transactions, we use the instance of the FragmentTransaction as shown


below:

FragmentTransaction ft=FragmentManager.beginTransaction();

 beginTransaction() method is used to create FragmentTransaction


 The following code shows how to add a fragment:
FragmentManager fm=getFragmentManager();

FragmentTransaction ft=FragmentTransaction.beginTransaction();

Fragment1Activity fragment=new Fragment1Activity();

ft.add(R.id.fragment_container, fragment, “TAG1”);

ft.commit();

 Here Fragment1Activity is user defined java class of the fragment, which is also used to load the
UI of the fragment from XML file.

Dept of CSE, C.B.I.T,PDTR Page 38


Unit-4

 fragment_container is the ID of the container that exists in the layout file where we want to
put our fragment

 TAG1 refers to the unique ID to identify and access the fragment.

 The commit() method is used to apply the changes.

Creating Special Fragments:


Creating a ListFragment:

 A ListFragment is a fragment that contains a built-in ListView that can be set to display items
from a specified data source so we can directly add a java class file that extends ListFragment
class. In this java class file, we write code to define the items to be displayed through the
ListView of the ListFragment.

Fragment1Activity.java

import android.app.ListFragment;

import android.os.Bundle;

import android.widget.ArrayAdapter;

import android.view.View;

import android.widget.ListView;

import android.widget.TextView;

public class Fragment1Activity extends ListFragment

final String[ ] fruits={“Apple”, “ Mango”, “Orange”, “Grapes”, “Banana”};

@Override

public void onCreate(Bundle savedInstanceState)

Super.onCreate(savedInstanceState);

ArrayAdapter<String> arradpt=new ArrayAdapter<String>(getActivity(),


android.R.layout.simple_List_item_1, fruits);

Dept of CSE, C.B.I.T,PDTR Page 39


Unit-4

setListAdapter(arradpt);

@Override

public void onListItemClick(ListView1, View v, int position, long id)

TextView tv=(TextView)getActivity.findViewById(R.id.tv);

tv.setText(“You have selected”+((Textview) v)getText().toString());

activity_list_frag_app.xml

<LinearLayout

xmlns:android=http://schemas.android.com/apk/res/android

android:layout_width=“match_parent”

android:layout_height=“match_parent”

android:Orientation=“vertical”>

<fragment

android:name=“com.androidunleashed.listfragapp.Fragment1Activity”

android:layout_width=“wrap_content”

android:layout_height=“match_parent”

android:id=“@+id/fragment1”/>

</LinearLayout>

ListFragAppActivity.java

import android.app.Activity;

import android.os.Bundle;

import android.view.Menu;

public class ListFragAppActivity extends Activity


Dept of CSE, C.B.I.T,PDTR Page 40
Unit-4

@Override

public void onCreate(Bundle savedInstanceState)

Super.onCreate(savedInstanceState);

setContentView(R.layout.activity_list_frag_app);

@Override

public boolean onCreateOptioneMenu(Menu menu)

getMenuInflater.inflate(R.menu.activity_list_frag_app,menu);

return true;

Dept of CSE, C.B.I.T,PDTR Page 41

You might also like