Important Announcement
PubHTML5 Scheduled Server Maintenance on (GMT) Sunday, June 26th, 2:00 am - 8:00 am.
PubHTML5 site will be inoperative during the times indicated!

Home Explore CU-BCA-SEM-V-Mobile Application Development-Second Draft

CU-BCA-SEM-V-Mobile Application Development-Second Draft

Published by Teamlease Edtech Ltd (Amita Chitroda), 2022-02-26 01:58:23

Description: CU-BCA-SEM-V-Mobile Application Development-Second Draft

Search

Read the Text Version

Step Description 1 You will use Android studio IDE to create an Android application and name it as demo under a package com example demo as explained in the Hello WorldExample chapter. 2 Modify MainActivity.java file to add a click event. 3 Modify the default content of res/layout/activity_main.xml file to include Android UI control. 4 Define required necessary string constants in res/values/strings.xml file 5 Run the application to launch Android emulator and verify the result of the changes done in the application. Table 5.3: EditText Attributes 3 Let's try to run your demo application. I assume you had created your AVD while doing environment setup. To run the app from Android studio, open one of your project's activity files and click Run icon from the toolbar. Android Studio installs the app on your AVD and starts it and if everything is fine with your setup and application, it will display following Emulator window − 101 CU IDOL SELF LEARNING MATERIAL (SLM)

Figure 5.2: EDIT TEXT 5.5 SUMMARY  A View occupies a rectangular area on the screen and is responsible for drawing and event handling. View is the base class for widgets, which are used to create interactive UI components. The ViewGroup subclass is the base class for layouts, which are invisible containers that hold other Views and define their layout properties.  All of the views in a window are arranged in a single tree. You can add views either from code or by specifying a tree of views in one or more XML layout files. There are many specialized subclasses of views that act as controls or are capable of displaying text, images, or other content.  The geometry of a view is that of a rectangle. A view has a location, expressed as a pair of left and top coordinates, and two dimensions, expressed as a width and a height. The unit for location and dimensions is the pixel.  All of the views in a window are arranged in a single tree. You can add views either from code or by specifying a tree of views in one or more XML layout files. There are many specialized subclasses of views that act as controls or are capable of displaying text, images, or other content.  The framework will handle routine focus movement in response to user input. This includes changing the focus as views are removed or hidden or as new views become available. Views indicate their willingness to take focus through theFocusablemethod. To change whether a view can take focus, call setFocusable.  By default, Views are created using the theme of the Context object supplied to their constructor; however, a different theme may be specified by using the android theme attribute in layout XML or by passing a ContextThemeWrapper to the constructor from code. 102 CU IDOL SELF LEARNING MATERIAL (SLM)

 Layout Managers are extensions of the View Group class and are used to position child Views within your UI. Layouts can be nested, letting you create arbitrarily complex UIs using a combination of layouts. The Android SDK includes a number of layout classes.  A defining feature of the layout classes described previously, and the techniques described for using them within your apps, is their ability to scale and adapt to a wide range of screen sizes, resolutions, and orientations. The variety of Android devices is a critical part of its success. For developers, this diversity introduces a challenge for designing UIs to ensure that they provide the best possible experience for users, regardless of which Android device they own.  In Android, TextView displays text to the user and optionally allows them to edit it programmatically. TextView is a complete text editor, however basic class is configured to not allow editing but we can edit it. 5.6 KEYWORDS  Linear Layout is one of the simplest layout classes. It allows you to create simple UIs (or UI elements) that align a sequence of child Views in either a vertical or a horizontal line. The simplicity of the Linear Layout makes it easy to use but limits its flexibility.  View is a basic building block of UI in android. A view is a small rectangular box that responds to user inputs. E.g.: EditText, Button, CheckBox, etc. ViewGroup is an invisible container of other views and other ViewGroup.  Layoutdefines 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.  TextView displays text to the user and optionally allows them to edit it. A TextView is a complete text editor; however the basic class is configured to not allow editing.  EditText is a user interface control which is used to allow the user to enter or modify the text. In android, we can create EditText control in two ways either in XML layout file or create it in Activity file programmatically. 5.7 LEARNING ACTIVITY 1. Find the ALL different layout of smartphone & tablets ___________________________________________________________________________ __________________________________________________________________________ 103 CU IDOL SELF LEARNING MATERIAL (SLM)

2. How will you use the text view in your android phone? ___________________________________________________________________________ __________________________________________________________________________ 5.8 UNIT END QUESTIONS A. Descriptive Questions Short Questions 1. What isView? 2. Discuss Edit Text. 3. What are UI Controls? 4. Explain Text View. 5. Write a short on Layouts. Long Questions 1. Describe View. 2. Briefly explain Linear, Relative & Constraint Layouts. 3. Discuss about UI Controls. 4. Explain Text View. 5. Discuss aboutLayouts. B. Multiple Choice Questions 1. What is the default layout in android application? a. RelativeLayout b. TableLayout c. LinearLayout d. FrameLayout 2. Which control you will use to display text? a. EditText b. TextView c. label d. None of these. 3. Which view you will use To embed a web browser in your activity? 104 CU IDOL SELF LEARNING MATERIAL (SLM)

a. RichTextView b. Browser c. WebView d. None of these. 4. What is anchor view? a. Same as list view b. provides the information on respective relative positions c. Same as relative layout d. None of these 5. . What is contained within the Layout xml file? a. Orientations and layouts that specify what the display looks like b. The permissions required by the app c. The strings used in the app d. The code which is compiled to run the app Answer 1-a, 2- b, 3-c, 4- b, 5- a 5.9 REFERENCES Reference  Zigurd Mednieks, Laird Dornin, Blake Meike G, and Masumi Nakamura, 2011 “Programming Android”, O’Reilly books.  2012 Smashing Android UI (Smashing Magazine Book Series) Paperback – Import,  Dave Smith and Geoff Friesen, 2011, Android Recipes: A Problem-Solution Approach. Textbooks  Mitchell Schuler, 2016, Android Programming: Mastering Course for Beginners.  Wei - Meng Le, 2012, Beginning Android 4 Application Development”, John Wiley & Sons, Inc.  Reto Meier, 2012, Professional Android 4 Application Development”, John Wiley & Sons, Inc. 105 CU IDOL SELF LEARNING MATERIAL (SLM)

Websites  https://data-flair.training/  https://www.tutorialspoint.com/  https://www.javatpoint.com/  https://www.careerride.com/ 106 CU IDOL SELF LEARNING MATERIAL (SLM)

UNIT 6: ANDROID VIEW PART 2 STRUCTURE 6.0 Learning Objectives 6.1 Introduction 6.2 Button 6.3 Radio Group 6.4 Radio Button Checkbox 6.5 Image View 6.5.1 Toggle Button 6.5.2 Spinner 6.5.3 List View 6.6 Summary 6.7 Keywords 6.8 Learning Activity 6.9 Unit End Questions 6.10 References 6.0 LEARNING OBJECTIVES After studying this unit, you will be able to:  Outline the importance of Button.  Explain the Radio Group.  Explain the Image View.  Understand Radio Button Checkbox.  Describe the List View.  Explain Toggle Button & Spinner. 6.1 INTRODUCTION Android Button represents a push-button. The android widget Button is subclass of TextView class and CompoundButton is the subclass of Button class. There are different types of buttons in android such as RadioButton, ToggleButton, and Compound Button etc. 107 CU IDOL SELF LEARNING MATERIAL (SLM)

In Android applications, a Button is a user interface that is used to perform some action when clicked or tapped. It is a very common widget in Android and developers often use it. This article demonstrates how to create a button in Android Studio. A radio button or option button is a graphical control element that allows the user to choose only one of a predefined set of mutually exclusive options. The singular property of a radio button makes it distinct from a checkbox, which allows more than one item to be selected and for the unselected state to be restored. Radio buttons are arranged in groups of two or more and displayed on screen as, for example, a list of circular holes that can contain white space or a dot. Each radio button is normally accompanied by a label describing the choice that the radio button represents. The choices are mutually exclusive; when the user selects a radio button, any previously selected radio button in the same group becomes deselected Selecting a radio button is done by clicking the mouse on the button, or the caption, or by using a keyboard shortcut. It is possible that initially none of the radio buttons in a group are selected. This unselected state cannot be restored by interacting with the radio button widget, though it may be possible through other user interface elements. When used in an HTML form, if no button in a group is checked, then no name value pair is passed when the form is submitted. For example, for a radio button group named Sex with the options Male and Female, the variable Sex would not be passed, even with a blank value. Radio button have only 2 states namely- True & False. Checkboxes have 3 states namely- Checked, unchecked & indeterminate. It is used when you want to limit the user’s choice to just one option from the range provided. It is used when you want to allow user to select multiple choices. Image View and Image Button are used in Android application to place an image in the view. ImageButton is used to use an image as a button in your android application.ImageView is a public class in Android that is used to upload and display images in Android Applications. ImageView is used to set the height, width, id, and other attributes of the image in the Android Spinner is just a drop-down list like what’s seen in other programming languages such as in HTML pages. In Android, Spinner is used to select one value from a set of values. In the default state, a spinner shows its currently selected value. Touching the spinner displays a drop-down menu with all other available values, from which the user can select a new one. Android spinner is associated with AdapterView. So, we need to set the adapter class with the Spinner, Android Drop Donation according to the screen size of the Android Device. In Android, ToggleButton is used to display checked and unchecked state of a button. ToggleButton basically an off/on button with a light indicator which indicates the current state of toggle button. The simplest example of ToggleButton is doing on/off in sound, Bluetooth, WI-FI, hotspot etc. It is a subclass of compoundButton. Android ListView is a view which groups several items and display them in vertical scrollable list. The list items are automatically inserted to the list using an Adapter that pulls content from a source such as an array or database. 108 CU IDOL SELF LEARNING MATERIAL (SLM)

6.2 BUTTON Android Button represents a push-button. The android widget Button is subclass of TextView class and CompoundButton is the subclass of Button class. There are different types of buttons in android such as RadioButton, ToggleButton, and CompoundButton etc. Example: Android Button represents a push-button. The android.widget.Button is subclass of TextView class and CompoundButton is the subclass of Button class. There are different types of buttons in android such as RadioButton, ToggleButton, CompoundButton etc. Android Button Example with Listener Here, we are going to create two textfields and one button for sum of two numbers. If user clicks button, sum of two input values is displayed on the Toast. We can perform action on button using different types such as calling listener on button or adding onClick property of button in activity's xml file. 1. Button set On Click Listener 2. @Override 3. public void on Click 4. //code Drag the component or write the code for UI in activity_main.xml First, drag 2 textfields from the Text Fields palette and one button from the Form Widgets palette. 6.3 RADIO GROUP This class is used to create a multiple-exclusion scope for a set of radio buttons. Checking none radio button that belongs to a radio group uncheck any previously checked radio button within the same group. Initially, all the radio buttons are unchecked. While it is not possible to uncheck a particular radio button, the radio group can be cleared to remove the checked state. Example: Following is the example of defining multiple RadioButton controls in RadioGroup, one TextView control and one Button control in RelativeLayout to get the selected values of RadioButton controls when we click on Button in the android application. The selection is identified by the unique id of the radio button as defined in the XML layout file.A RadioGroup class is used for set of radio buttons. 109 CU IDOL SELF LEARNING MATERIAL (SLM)

If we check one radio button that belongs to a radio group, it automatically uncheck any previously checked radio button within the same group. RadioGroup Attributes Following are the important attributes related to RadioGroup control. You can check Android official documentation for complete list of attributes and related methods which you can use to change these attributes are run time. Attribute Description android:checkedButton This is the id of child radio button that should be checked by default within this radio group. Table 6.1: RadioGroup Attributes 1 Inherited from Android View Class Sr.No. Attribute & Description 1 android:background This is a draw able to use as the background. 2 android:contentDescription This defines text that briefly describes content of the view. 3 android:id This supplies an identifier name for this view 4 android:onClick This is the name of the method in this View's context to invoke when the view is clicked. 5 android:visibility 110 CU IDOL SELF LEARNING MATERIAL (SLM)

This controls the initial visibility of the view. Table 6.2: RadioGroup Attributes 2 Example This example will take you through simple steps to show how to create your own Android application using Linear Layout and RadioGroup. Step Description 1 You will use Android studio IDE to create an Android application and name it as My Application under a package com.example.saira_000.myapplication; as explained in the Hello World Example chapter. 2 Modify src/MainActivity.java file to add a click event. 2 Modify the default content of res/layout/activity_main.xml file to include Android UI control. 3 No need to change default constants at res/values/strings.xml, android studio takes care of default constants. 4 Run the application to launch Android emulator and verify the result of the changes done in the application. Table 6.3: RadioGroup Attributes 3 Let's try to run your My Application application. I assume you had created your AVD while doing environment setup. To run the app from Android studio, open one of your project's activity files and click Run icon from the toolbar. Android studio installs the app on your AVD and starts it and if everything is fine with your setup and application, it will display following Emulator window The following screen will appear; here we have a RadioGroup. 111 CU IDOL SELF LEARNING MATERIAL (SLM)

Figure 6.1: RadioGroup Need to select male or female radio button then click on new button. If you do above steps without fail, you will get a toast message after clicked by new button 6.4 RADIO BUTTON CHECKBOXES 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. RadioButton is generally used with RadioGroup. RadioGroup contains several radio buttons, marking one radio button as checked makes all other radio buttons as unchecked. Checkboxes allow the user to select one or more options from a set. Typically, you should present each checkbox option in a vertical list. To create each checkbox option, create a CheckBox in your layout. Because a set of checkbox options allows the user to select multiple items, each checkbox is managed separately, and you must register a click listener for each one. A key class is the following: 112 CU IDOL SELF LEARNING MATERIAL (SLM)

CheckBox Responding to Click Events When the user selects a checkbox, the CheckBox object receives an on-click event. To define the click event handler for a checkbox, add the android: on Click attribute to the <CheckBox> element in your XML layout. The value for this attribute must be the name of the method you want to call in response to a click event. The Activity hosting the layout must then implement the corresponding method. The method you declare in the android:onClick attribute must have a signature exactly as shown above? Specifically, the method must: Be public Return void Define a View as its only parameter (this will be the View that was clicked) A CheckBox is an on/off switch that can be toggled by the user. You should use checkboxes when presenting users with a group of selectable options that are not mutually exclusive. Figure 6.2: CheckBox 1 CheckBox Attributes Following are the important attributes related to CheckBox control. You can check Android official documentation for complete list of attributes and related methods which you can use to change these attributes are run time. Inheritedfrom Android, Widget, Text View Class Sr. No Attribute & Description 113 CU IDOL SELF LEARNING MATERIAL (SLM)

android:autoText 1 If set, specifies that this TextView has a textual input method and automatically corrects some common spelling errors. android: draw able Bottom 2 This is the draw able to be drawn below the text. android: draw able Right 3 This is the draw able to be drawn to the right of the text. android:editable 4 If set, specifies that this TextView has an input method. android:text 5 This is the Text to display. Table 6.4: CheckBox Attributes 1 Inherited from Android View Class Sr. No Attribute & Description android:background 1 This is a draw able to use as the background. android:contentDescription 2 This defines text that briefly describes content of the view. 3 android:id 114 CU IDOL SELF LEARNING MATERIAL (SLM)

This supplies an identifier name for this view. android:onClick 4 This is the name of the method in this View's context to invoke when the view is clicked. android:visibility 5 This controls the initial visibility of the view. Table 6.5: CheckBox Attributes 2 Example This example will take you through simple steps to show how to create your own Android application using Linear Layout and CheckBox. Step Description 1 You will use Android Studio IDE to create an Android application and name it as myapplication under a package com.example.myapplication as explained in the Hello World Example chapter. 2 Modify src/MainActivity.java file to add a click event. 3 Modify the default content of res/layout/activity_main.xml file to include Android UI control. 4 No need to declare default string constants. Android studio takes care of default constants at string.xml 5 Run the application to launch Android emulator and verify the result of the changes done in the application. 115 CU IDOL SELF LEARNING MATERIAL (SLM)

Table 6.6: CheckBox Attributes 3 Let's try to run your MyApplication application. I assume you had created your AVD while doing environment setup. To run the app from Android studio, open one of your project's activity files and click Run icon from the toolbar. Android studio installs the app on your AVD and starts it and if everything is fine with your setup and application, it will display following Emulator window − Figure 6.3: CheckBox 2 User needs you check on either do you like android check box or do you like tutorials point check box and press ok button, if does all process correctly, it gonna be shown toast message as Thanks. Or else do press on cancel button if user presses cancel button it going to close the application. 6.5 IMAGE VIEW ImageView in Android with Example ImageView class is used to display any kind of image resource in the android application either it can be android graphics, Bitmap or android graphics draw able. Draw able, ImageView class or android.Widget. ImageView inherits the android. view.View class which is the subclass of Kotlin Any class. Application of ImageView is also in applying tints to an image to reuse a draw able resource and create overlays on background images. Moreover, ImageView is also used to control the size and movement of an image. Adding an ImageView to an activity Whenever ImageView is added to an activity, it means there is a requirement for an image resource. Thus, it is oblivious to provide an Image file to that ImageView class. It can be done by adding an image file that is present in the Android Studio itself or we can add our own image file. Android Studio owns a wide range of draw able resources which are very 116 CU IDOL SELF LEARNING MATERIAL (SLM)

common in the android application layout. The following are the steps to add a draw able resource to the ImageView class. Note: The steps are performed on Android Studio version 4.0 Open the activity_main.xml file in which the image is to be added Activity.xml file in which image is to be added Switch from code view to the design view of the activity_main.xml file. Design view of the activity.xml file For adding an image from Android Studio Drag the ImageView widget to the activity area of the application, a pop-up dialogue box will open choose from the wide range of draw able resources and click “OK”. Adding a draw able resource to the activity For adding an image files other than Android Studio draw able resources: Click on the “Resource Manager” tab on the leftmost panel and select the “Import Drawables” option. Select Import Drawables option to add image file Select the path of the image file on your computer and click “OK”. After that set, the “Qualifier type” and “value” of the image file according to your need and click “Next” then “Import”. Providing value to Qualifier type for the image Drag the ImageView class in the activity area, a pop-up dialogue box will appear which contain your imported image file. Choose your image file and click “OK”, your image will be added to the activity. Adding image to the activity Note: After adding an image set its constraints layout both vertically and horizontally otherwise it will show an error. XML Attributes of ImageView XML Attribute Description Android:id to uniquely identify an image view Android:src/app:srcCompat to add the file path of the inserted image android:background To provide a background colour to the inserted image Android: layout width to set the width of the image 117 CU IDOL SELF LEARNING MATERIAL (SLM)

Android: layout height to set the height of the image Android: padding to add padding to the image from left, right, top, or bottom of the view Android:scaleType to re-size the image or to move it to fix its size Example Step by Step Implementation Step 1: Create a New Project To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Step 2: Working with the activity_main.xml file Navigate to the app > res > layout > activity_main.xml and add the below code to that file. Below is the code for the activity_main.xml file.  <?xml version=\"1.0\" encoding=\"utf-8\"?>  <androidx.constraintlayout.widget.ConstraintLayout  xmlns: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=\".MainActivity\">  <ImageView  android:id=\"@+id/GfG_full_logo\"  android:layout_width=\"0dp\"  android:layout_height=\"wrap_content\"  app:layout_constraintBottom_toBottomOf=\"parent\"  app:layout_constraintEnd_toEndOf=\"parent\"  app:layout_constraintStart_toStartOf=\"parent\"  app:layout_constraintTop_toTopOf=\"parent\"  app:layout_constraintVertical_bias=\"0.078\"  app:srcCompat=\"@drawable/full_logo\" /> 118 CU IDOL SELF LEARNING MATERIAL (SLM)

 <ImageView  android:id=\"@+id/GfG_logo\"  android:layout_width=\"wrap_content\"  android:layout_height=\"wrap_content\"  app:layout_constraintBottom_toBottomOf=\"parent\"  app:layout_constraintEnd_toEndOf=\"parent\"  app:layout_constraintStart_toStartOf=\"parent\"  app:layout_constraintTop_toBottomOf=\"@+id/GfG_full_logo\"  app:srcCompat=\"@drawable/logo\" />  </androidx.constraintlayout.widget.ConstraintLayout> Note: All the attributes of the ImageView which are starting with app:layout_constraint are the vertical and horizontal constraints to fix the image position in the activity. This is very necessary to add the constraint to the ImageView otherwise; all the images will take the position (0, 0) of the activity layout. Step 4: Working with the MainActivity file Go to the MainActivity file and refer to the following code. Below is the code for the MainActivity file. Comments are added inside the code to understand the code in more detail. Since in the activity, only 2 images have been added and nothing else is being done like touching a button, etc. So, the MainActivity file will simply look like the below code. 6.5.1 Toggle Button Android Toggle Button can be used to display checked/unchecked (On/Off) state on the button. It is beneficial if user must change the setting between two states. It can be used to on/Off Sound, Wifi, and Bluetooth etc. Example: 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, and 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. 119 CU IDOL SELF LEARNING MATERIAL (SLM)

Figure 6.4: Toggle button 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 Compound Button class Android ToggleButton class. ToggleButton class provides the facility of creating the toggle button. XML Attributes of ToggleButton class The 3 XML attributes of ToggleButton class. XML Attribute Description android:disabledAlpha The alpha to apply to the indicator when disabled. android:textOff The text for the button when it is not checked. android:textOn The text for the button when it is checked. Table 6.7: Toggle button 1 Methods of ToggleButton class The widely used methods of ToggleButton class are given below. 120 CU IDOL SELF LEARNING MATERIAL (SLM)

Method Description CharSequence getTextOff() Returns the text when button is not in the checked state. CharSequence getTextOn() Returns the text for when button is in the checked state. void setChecked(Boolean checked) Changes the checked state of this button. Table 6.8: Toggle button 2 6.5.2 Spinner Android Spinner is a view similar to the dropdown list which is used to select one option from the list of options. It provides an easy way to select one item from the list of items and it shows a dropdown list of all values when we click on it. The default value of the android spinner will be the currently selected value and by using Adapter we can easily bind the items to the spinner objects. Generally, we populate our Spinner control with a list of items by using an ArrayAdapter in our Kotlin file. Example: 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 AsbSpinner class. In this example, 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.android.com/ap k/res/android\" 121 CU IDOL SELF LEARNING MATERIAL (SLM)

xmlns:app=\"http://schemas.android.com/apk/res-auto\" 122 xmlns:tools=\"http://schemas.android.com/tools\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" tools:context=\"example.javatpoint.com.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 example.javatpoint.com.spinner; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; CU IDOL SELF LEARNING MATERIAL (SLM)

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); } //Performing action onItemSelected and onNothing selected @Override public void onItemSelected(AdapterView<?> arg0, View arg1, int position, long id) { 123 CU IDOL SELF LEARNING MATERIAL (SLM)

Toast.makeText(getApplicationContext(),country[position] , Toast.LENGTH_LONG).show(); } @Override public void onNothingSelected(AdapterView<?> arg0) { // TODO Auto-generated method stub } } Output: Figure 6.5: Output of Spinner 124 CU IDOL SELF LEARNING MATERIAL (SLM)

Figure 6.6: Output of Spinner 6.5.3 List View Android ListView is a view which groups several items and display them in vertical scrollable list. The list items are automatically inserted to the list using an Adapter that pulls content from a source such as an array or database. A View Group that creates and manages a vertical list of Views, displaying them as rows within the list. The simplest List View displays the String value of each object in an array, using a Text View for each item. An adapter bridges between UI components and the data source that fill data into UI Component. Adapter holds the data and sends the data to adapter view, the view can take the data from adapter view and shows the data on different views like as spinner, list view, grid view etc. The ListView and GridView are subclasses of AdapterView, and they can be populated by binding them to an Adapter, which retrieves data from an external source and creates a View that represents each data entry. Android provides several subclasses of Adapter that are useful for retrieving different kinds of data and building views for an AdapterView , The common adapters are 125 CU IDOL SELF LEARNING MATERIAL (SLM)

ArrayAdapter,Base Adapter, CursorAdapter, SimpleCursor Adapter,SpinnerAdapter and WrapperListAdapter. We will see separate examples for both the adapters. ListView Attributes Following are the important attributes specific to GridView − Sr.No Attribute & Description 1 android:id This is the ID which uniquely identifies the layout. 2 android:divider This is draw able or colour to draw between list items. 3 android:dividerHeight This specifies height of the divider. This could be in px, dp, sp, in, or mm. 4 android:entries Specifies the reference to an array resource that will populate the ListView. 5 android:footerDividersEnabled When set to false, the ListView will not draw the divider before each footer view. The default value is true. 6 android:headerDividersEnabled When set to false, the ListView will not draw the divider after each header view. The default value is true. ArrayAdapter Table 6.9: ListView Attributes 1 CU IDOL SELF LEARNING MATERIAL (SLM) 126

You can use this adapter when your data source is an array. By default, ArrayAdapter creates a view for each array item by calling to String on each item and placing the contents in a TextView. Consider you have an array of strings you want to display in a ListView, initialize a new ArrayAdapter using a constructor to specify the layout for each string and the string array Here are arguments for this constructor ArrayAdapter = new ArrayAdapter<String>;  First argument this is the application context. Most of the case, keep it this.  Second argument will be layout defined in XML file and having TextView for each string in the array.  Final argument is an array of strings which will be populated in the text view.  Once you have array adapter created, then simply call setAdapter on your ListView object as follows You will define your list view under res/layout directory in an XML file. For our example we are going to using activity_main.xml file. Example Following is the example which will take you through simple steps to show how to create your own Android application using ListView. Follow the following steps to modify the Android application we created in Hello World Example chapter Step Description 1 You will use Android Studio IDE to create an Android application and name it as ListDisplay under a package com example ListDisplay as explained in the Hello World Example chapter. 2 Modify the default content of res/layout/activity_main.xml file to include ListView content with the self-explanatory attributes. 3 No need to change string.xml, Android studio takes care of default string constants. 4 Create a Text View file res/layout/activity_listview.xml. This file will have setting to 127 CU IDOL SELF LEARNING MATERIAL (SLM)

display all the list items. So you can customize its fonts, padding, colour etc. using this file. 6 Run the application to launch Android emulator and verify the result of the changes done in the application. Table 6.10: ListView Attributes 2 Let's try to run our modified Hello World! Application we just modified. I assume you had created your AVD while doing environment set-up. To run the app from Android studio, open one of your project's activity files and click Run icon from the tool bar. Android studio installs the app on your AVD and starts it and if everything is fine with your set-up and application, it will display following Emulator window − Figure 6.5: My application 6.6 SUMMARY  Android Button represents a push-button. The android widget Button is subclass of TextView class and CompoundButton is the subclass of Button class. There are different types of buttons in android such as RadioButton, ToggleButton, and Compound Button etc.  Android Button represents a push-button. The android widget Button is subclass of Text View class and CompoundButton is the subclass of Button class. 128 CU IDOL SELF LEARNING MATERIAL (SLM)

 Android Toggle Button can be used to display checked/unchecked (On/Off) state on the button. It is beneficial if user must change the setting between two states. It can be used to On/Off Sound, Wifi, Bluetooth etc.  This class is used to create a multiple-exclusion scope for a set of radio buttons. CheckingNone radio button that belongs to a radio group uncheck any previously checked radio button within the same group. Initially, all the radio buttons are unchecked. While it is not possible to uncheck a particular radio button, the radio group can be cleared to remove the checked state.  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.  Android Spinner is a view like the dropdown list which is used to select one option from the list of options. It provides an easy way to select one item from the list of items and it shows a dropdown list of all values when we click on it. The default value of the android spinner will be the currently selected value and by using Adapter we can easily bind the items to the spinner objects. Generally, we populate our Spinner control with a list of items by using an ArrayAdapter in our Kotlin file.  Checkboxes allow the user to select one or more options from a set. Typically, you should present each checkbox option in a vertical list.  To create each checkbox option, create a CheckBox in your layout. Because a set of checkbox options allows the user to select multiple items, each checkbox is managed separately, and you must register a click listener for each one.  The ListView and GridView are subclasses of AdapterView, and they can be populated by binding them to an Adapter, which retrieves data from an external source and creates a View that represents each data entry.  Android Toggle Button can be used to display checked/unchecked (On/Off) state on the button. It is beneficial if user must change the setting between two states. It can be used to On/Off Sound, Wi-Fi, and Bluetooth etc. 6.7 KEYWORDS  Android Button represents a push-button. The android Button is subclass of TextView class and CompoundButton is the subclass of Button class. There are different types of buttons in android such as RadioButton, ToggleButton, and CompoundButton etc. 129 CU IDOL SELF LEARNING MATERIAL (SLM)

 Radio group is defined by giving each of radio buttons in the group the same name. Once a radio group is established, selecting any radio button in that group automatically deselects any currently-selected radio button in the same group.  ImageView class is used to display any kind of image resource in the android application either it can be android, graphics, Bitmap or android. Graphics Application of ImageView is also in applying tints to an image in order to reuse a draw able resource and create overlays on background images  ToggleButton basically an off/on button with a light indicator which indicates the current state of toggle button. The simplest example of ToggleButton is doing on/off in sound, Bluetooth, WIFI, hotspot etc. It is a subclass of compoundButton.  List view is an adapter view that does not know the details, such as type and contents, of the views it contains. Instead list view requests views on demand from a ListAdapter as needed, such as to display new views as the user scrolls up or down. In order to display items in the list, call set Adapter 6.8 LEARNING ACTIVITY 1. Find the article on Android button. ___________________________________________________________________________ __________________________________________________________________________ 2. Find the checkbox in your phone. ___________________________________________________________________________ __________________________________________________________________________ 6.9 UNIT END QUESTIONS A. Descriptive Questions Short Questions 1. Describe the Button. 2. What is Radio Group? 3. Write a note on Radio Button Checkbox. 4. Explain Toggle Button. 5. Explain need theory. Long Questions 1. Explain Button. 130 CU IDOL SELF LEARNING MATERIAL (SLM)

2. Describe the Radio Group. 3. Discuss the Radio Button Checkbox. 4. Explain Image View. 5. Explain Toggle Button and Spinner. B. Multiple Choice Questions 1. What does click mean in android UI? a. class b. button c. property d. function 2. What is a method that is used to handle after clicking a button is? a. OnCreate b. OnSelect c. OnClick d. OnDo 3. What is the required android environment for development is called as? a. SDK b. IDE c. APK d. JDK 4. Which of the following component has view hierarchies that control screen format and appearance of the views? a. Layouts b. Views c. Resources d. Manifest 5. Which of the following component has UI elements that are drawn on-screen 131 including buttons, lists forms etc? a. Fragments b. Views c. Resources CU IDOL SELF LEARNING MATERIAL (SLM)

d. Manifest Answer 1-c, 2- c, 3-a, 4- a, 5- b 6.10 REFERENCES Reference  Oracle Exadata Recipes: 2013, A Problem-Solution ApproachJohn Clarke.  Zigurd Mednieks, Laird Dornin, Blake Meike G, and Masumi Nakamura, 2011 “Programming Android”, O’Reilly books.  Go Recipes: 2016, A Problem-Solution Shiju Varghese. Textbooks  Jeff Friesen, Dave Smith, 2011, Android Recipes: A Problem-Solution Approach books.  Wei - Meng Le, 2012, Beginning Android 4 Application Development”, John Wiley & Sons, Inc.  Reto Meier, 2012, Professional Android 4 Application Development”, John Wiley & Sons, Inc. Websites  https://en.wikipedia.org/  https://developer.android.com/  https://www.tutorialspoint.com/ 132 CU IDOL SELF LEARNING MATERIAL (SLM)

UNIT 7: ANDROID VIEW PART 3 STRUCTURE 7.0 Learning Objectives 7.1 Introduction 7.2 Intents and Its Types 7.2.1 Implicit Intents 7.2.2 Explicit Intents 7.3 Toast 7.4 Splash Screen 7.5 Summary 7.6 Keywords 7.7 Learning Activity 7.8 Unit End Questions 7.9 References 7.0 LEARNING OBJECTIVES After studying this unit, you will be able to:  Know Intents and its Types  Learn Implicit Intents.  Define Splash Screen.  Explain Toast. 7.1 INTRODUCTION This Module looks at Intents probably the most unique and important concept in Android development. You’ll learn how to use Intents to broadcast data within and between applications and how to listen for them to detect changes in the system state. You’ll also learn how to define implicit and explicit Intents to start Activities or Services using late runtime binding. Using implicit Intents, you’ll learn how to request that an action be performed on a piece of data, enabling Android to determine which application components can best service that request. Broadcast Intents are used to announce events systemwide. You’ll learn how to transmit these broadcasts and receive those using Broadcast Receivers. 133 CU IDOL SELF LEARNING MATERIAL (SLM)

Intent is to perform an action on the screen. It is mostly used to start activity, send broadcast receiver, start services, and send message between two activities. There are two intents available in android as Implicit Intents and Explicit Intents. Here is a sample example to start new activity with old activity. An Android Toast is a small message displayed on the screen, like a tool tip or other similar popup notification. A Toast is displayed on top of the main content of an activity, and only remains visible for a short time. A toast provides simple feedback about an operation in a small popup. It only fills the amount of space required for the message and the current activity remains visible and interactive. Toasts automatically disappear after a timeout. Android Toast can be used to display information for the short period of time. A toast contains message to be displayed quickly and disappears after some time, The android widget. Toast class is the subclass of java 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. A splash screen is mostly the first screen of the app when it is opened. It is a constant screen which appears for a specific amount of time, generally shows for the first time when the app is launched. Android 12 ads the Splash Screen API, which enables a new app launch animation for all apps. This includes an into-app motion at launch, a splash screen showing your app icon, and a transition to your app itself. The new experience brings standard design elements to every app launch, but it’s also customizable so your app can maintain its unique branding.Splash Screen is most commonly the first start-up screen which appears when App is opened. In other words, it is a simple constant screen for a fixed amount of time which is used to display the company logo, name, advertising content etc. Normally it shows when app is first time launched on android device or it may be process that is used to show screen to user just before the app loads completely. In any mobile app, Splash Screen is the first thing that the user will see. Despite this I have seen many developers implement splash screen with a fixed timeout, making the users of their app wait even though the app is not doing any initialization. 7.2 INTENTS AND ITS TYPES Intents are used as a message-passing mechanism that works both within your application and between applications. You can use Intents to do the following:  Explicitly start a particular Service or Activity using its class name  Start an Activity or Service to perform an action with (or on) a particular piece of data  Broadcast that an event has occurred You can use Intents to support interaction among any of the application components installed on an Android device, no matter which application they’re a part of. This turns your device 134 CU IDOL SELF LEARNING MATERIAL (SLM)

from a platform containing a collection of independent components into a single, interconnected system. One of the most common uses for Intents is to start new Activities, either explicitly or implicitly. In the latter case the action does not need to be performed by an Activity within the calling application. You can also use Intents to broadcast messages across the system. Applications can register Broadcast Receivers to listen for, and react to, these Broadcast Intents. This enables you to create event-driven applications based on internal, system, or third-party application events. Android broadcasts Intents to announce system events, such as changes in Internet connectivity or battery charge levels. The native Android applications, such as the Phone Dialler and SMS Manager, simply register components that listen for specific Broadcast Intents such as “incoming phone call” or “SMS message received” and react accordingly. As a result, you can replace many of the native applications by registering Broadcast Receivers that listen for the same Intents. Using Intents, rather than explicitly loading classes, to propagate actions even within the same application is a fundamental Android design principle. It encourages the decoupling of components to allow the seamless replacement of application elements. It also provides the basis of a simple model for extending an application’s functionality. Using Intents to Launch Activities The most common use of Intents is to bind your application components and communicate between them. Intents are used to start Activities, allowing you to create a workflow of different screens. To create and display an Activity, call startsActivity, passing in Intent, as follows: startActivity. The startActivity method finds and starts the single Activity that best matches your Intent. You can construct the Intent to explicitly specify the Activity class to open, or to include an action that the target Activity must be able to perform. In the latter case, the run time will choose an Activity dynamically using a process known as intent resolution. When you use startActivity, your application won’t receive any notification when the newly launched Activity finishes, To track feedback from a sub-Activity, use startActivityForResult, as described later in this chapter. 7.2.1 Implicit Intent An implicit Intent is a mechanism that lets anonymous application components service action requests. That means you can ask the system to start an Activity to perform an action without knowing which application, or Activity, will be started. For example, to let users make calls from your application, you could implement a new dialler, or you could use an implicit Intent that requests the action be performed on a phone number.  if  Intent 135 CU IDOL SELF LEARNING MATERIAL (SLM)

 new Intent  start Activity Android resolves this Intent and starts an Activity that provides the dial action on a telephone number in this case, typically the Phone Dialler. When constructing a new implicit Intent, you specify an action to perform and, optionally, supply the URI of the data on which to perform that action. You can send additional data to the target Activity by adding extras to the Intent. Extras are a mechanism used to attach primitive values to Intent. You can use the overloaded putExtra method on any Intent to attach a new name / value pain that can then be retrieved using the corresponding getExtra method in the started Activity. The extras are stored within the Intent as a Bundle object that can be retrieved using the getExtras method. When you use an implicit Intent to start an Activity, Android will at run time resolve it into the Activity class best suited to performing the required action on the type of data specified. This means you can create projects that use functionality from other applications without knowing exactly which application you’re borrowing functionality from ahead of time. In circumstances where multiple Activities can potentially perform a given action, the user is presented with a choice. The process of intent resolution is determined through an analysis of the registered Broadcast Receivers, which are described in detail later in this chapter. Various native applications provide Activities capable of performing actions against specific data. Third-party applications, including your own, can be registered to support new actions or to provide an alternative provider of native actions. You’ll be introduced to some of the native actions, as well as how to register your own Activities to support them. Understanding an Implicit Intent In an earlier chapter you learned how to start an activity from an activity by specifying the class name of the activity to start in an explicit intent. This is the most basic way to use intent: To start Intent or other app component and pass data to it. A more flexible use of Intent is the implicit intent. You don't specify the exact activity to run instead, you include just enough information in the intent about the task you want to perform. The Android system matches the information in your request intent with any activity available on the device that can perform that task. If there's only one activity that matches, that activity is launched. If more than one activity matches the intent, the user is presented with an app chooser and picks which app they would like to perform the task. 136 CU IDOL SELF LEARNING MATERIAL (SLM)

Figure 7.1: Implicit Intent For example, you have an app that lists available snippets of video. If the user touches an item in the list, you want to play that video snippet. Rather than implementing an entire video player in your own app, you can launch an Intent that specifies the task as \"play an object of type video.\" The Android system then matches your request with an Activity that has registered itself to play objects of type video. An Activity registers itself with the system as being able to handle an implicitIntentwithIntentfilters, declared in the AndroidManifest.xml file. For example, the main Activity for your app has Intent filter that declares it the main Activity for the launcher category. This Intent filter is how the Android system knows to start that specific Activity in your app when the user taps the icon for your app on the device home screen. Intent Actions, Categories, and Data An implicit Intent, like an explicit Intent, is an instance of the Intent class. In addition to the parts of Intent you learned about in an earlier chapter, these fields are used by an implicit Intent:  The Intent action, which is the generic action the receiving Activity, should perform. The available Intent actions are defined as constants in the Intent class and begin with the word ACTION. A common Intent action is ACTION_VIEW, which you use when you have some information that an Activity can show to the user, such as a photo to view in a gallery app, or an address to view in a map app. You can specify the action for Intent in the Intent constructor, or with the set Action method.  An Intent category, which provides additional information about the category of component that, should handle the Intent. Intent categories are optional, and you can 137 CU IDOL SELF LEARNING MATERIAL (SLM)

add more than one category to Intent. Intent categories are also defined as constants in the Intent class and begin with the word CATEGORY. You can add categories to the Intent with the add Category method.  The data type, which indicates the MIME type of data the Activity, should operate on. Usually, the data type is inferred from the URI in the Intent data field, but you can also explicitly define the data type with the set Type method. Intent actions, categories, and data types are used both by the Intent object you create in your sending Activity, as well as in the Intent filters you define in the AndroidManifest.xml file for the receiving Activity. The Android system uses this information to match an implicit Intent request with an Activity or other component that can handle that Intent. Sending an Implicit Intent Starting an Activity with an implicit Intent, and passing data from one Activity to another, works much the same way as it does for an explicit Intent: 1. In the sending Activity, create a new Intent object. 2. Add information about the request to the Intent object, such as data or extras. 3. Send the Intent with start Activity (to just start the Activity) or start Activity for Result (to start the Activity and expect a result back). When you Create an Implicit Intent Object, you  Do not specify the specific Activity or other component to launch.  Add an Intent action or Intent categories.  Resolve the Intent with the system before calling start Activity or start Activity for Result.  Show an app chooser for the request. Create Implicit Intent Objects To use an implicit Intent, create an Intent object as you did for an explicit Intent, only without the specific component name.  Intent send Intent = new Intent;  You can also create the Intent object with a specific action:  Intent sendIntent = new Intent; Once you have an Intent object you can add other with the various Intent methods. For example, this code creates an implicit Intent object, sets the Intent action to ACTION_SEND, 138 CU IDOL SELF LEARNING MATERIAL (SLM)

defines an Intent extra to hold the text, and sets the type of the data to the MIME type \"text/plain\".  Intent send Intent = new Intent;  Send Intent set Action;  Send Intent putExtra;  Send Intent set Type; Resolve the Activity Before Starting it When you define an implicit Intent with a specific action and/or category, there is a possibility that there won't be any Activity on the device that can handle your request. If you just send the Intent and there is no appropriate match, your app will crash. To verify that an Activity or other component is available to receive your Intent, use the resolve Activity method with the system package manager like this: If the result of resolve Activity is not null, then there is at least one app available that can handle the Intent and it's safe to call start Activity. Do not send the Intent if the result is null. If you have a feature that depends on an external Activity that may or may not be available on the device, a best practice is to test for the availability of that, disable the feature or provide the user an error message for that feature. Show the app Chooser To find an Activity or other component that can handle your Intent requests, the Android system matches your implicit Intent with an Activity whose Intent filters indicate that they can perform that action. If there are multiple apps installed that match, the user is presented with an app chooser that lets them select which app they want to use to handle that Intent. In many cases the user has a preferred app for a given task, and they will select the option to always use that app for that task. However, if multiple apps can respond to the Intent and the user might want to use a different app each time, you can choose to explicitly show a chooser dialog every time. For example, when your app performs a \"share this\" action with the ACTION_SEND action, users may want to share using a different app depending on the current situation. To show the chooser, you create a wrapper Intent for your implicit Intent with the create Chooser method, and then resolve and call startActivity with that wrapper Intent. The createChoosermethod also requires a string argument for the title that appears on the chooser. You can specify the title with a string resource as you would any other string. 139 CU IDOL SELF LEARNING MATERIAL (SLM)

Receiving an Implicit Intent If you want an Activity in your app to respond to an implicit Intent (from your own app or other apps), declare one or moreIntentfilters in theAndroidManifest.xmlfile. Each Intent filter specifies the type of Intent it accepts based on the action, data, and category for the Intent. The system will deliver an implicit Intent to your app component only if that Intent can pass through one of your Intent filters. Intent filters  Define Intent filters with one or more <intent-filter> elements in the AndroidManifest.xml file, nested in the corresponding <activity> element. Inside <intent-filter>, specify the type of intent your activity can handle. The Android system matches an implicit intent with an activity or other app component only if the fields in the Intent object match the Intent filters for that component.  An Intent filter may contain the following elements, which correspond to the fields in the Intent object described above:  <Action>: The Intent action that the activity accepts.  <Data>: The type of data accepted, including the MIME type or other attributes of the data URI (such as scheme, host, port, and path).  <Category>: The Intent category. This Intent filter has the action MAIN and the category LAUNCHER. The <action> element specifies that this is the app's \"main\" entry point. The <category> element specifies that this activity should be listed in the system's app launcher (to allow users to launch the activity). Only the main activity for your app should have this Intent filter. You can specify more than one action, data, or category for the same Intent filter, or have multiple Intent filters per Activity to handle each different kind of Intent. The Android system tests an implicit Intent against an Intent filter by comparing the parts of that Intent to each of the three Intent filter elements (action, category, and data). The Intent must pass all three tests, or the Android system won't deliver the Intent to the component. However, because a component may have multiple Intent filters, an Intent that does not pass through one of a component's filters might make it through on another filter. Actions An Intent filter can declare zero or more <action> elements for the Intent action. The action is defined in the name attribute, and consists of the string \"android intentaction.\" plus the name of the Intent action, minus the ACTION_ prefix. So, for example, an implicit Intent with the action ACTION_VIEW matches an Intent filter whose action is android intent action. VIEW. 140 CU IDOL SELF LEARNING MATERIAL (SLM)

To get through this filter, the action specified in the incoming Intent object must match at least one of the actions. You must include at least one Intent action for an incoming implicit Intent to match. Categories An Intent filter can declare zero or more <category> elements for Intent categories. The category is defined in the name attribute andconsists of the string \"android intent category.\" plus the name of the Intent category, minus the CATEGORY prefix. Note that any Activity that you want to accept an implicit Intent must include the android intent category. DEFAULT Intent filter. This category is applied to all implicit Intent objects by the Android system. Data An Intent filter can declare zero or more <data> elements for the URI contained in the Intent data. As the Intent data consists of a URI and (optionally) a MIME type, you can create an Intent filter for various aspects of that data, including:  URI Scheme  URI Host  URI Path  Mime type Sharing Data using Share Compact IntentBuilder  Share actions are an easy way for users to share items in your app with social networks and other apps. Although you can build a share action in your own app using an implicit Intent with the ACTION_SEND action, Android provides the Share Compact Intent Builder helper class to easily implement sharing in your app.  Note: For apps that target Android releases after API 14, you can use the ShareActionProvider class for share actions instead of Share Compact IntentBuilder. The Share Compact class is part of the V4 support library and allows you to provide share actions in apps in a backward-compatible fashion. ShareCompact provides a single API for sharing on both old and new Android devices. You learn more about the Android support libraries in another chapter.  With the Share Compact IntentBuilder class, you do not need to create or send an implicit Intent for the share action. Use the methods in ShareCompact. IntentBuilder to indicate the data you want to share as well as any additional information. Start with the from method to create a new Intent builder, add other 141 CU IDOL SELF LEARNING MATERIAL (SLM)

methods to add more data, and end with the startChooser method to create and send the Intent. You can chain the methods together like this: ShareCompactIntentBuilder  .from(this) // information about the calling activity  .setType(mimeType) // mime type for the data  .setChooserTitle(\"Share this text with: \") //title for the app chooser  .setText(txt) // intent data  .startChooser(); // send the intent Managing Tasks In a previous chapter you learned about tasks and the back stack. The task for your app contains its own stack that contains each Activity the user has visited while using your app. As the user navigates around your app, Activity instances for that task are pushed and popped from the stack for that task. Most of the time the user's navigation from one Activity to another Activity and back again through the stack is straightforward. Depending on the design and navigation of your app there may be complications, especially with an Activity started from another For example, say you have an app with three Activity objects: A, B, and C. A launches B with an Intent, and B launches C. C, in turn sends an Intent to launch A. In this case the system creates a second instance of A on the top of the stack, rather than bringing the already-running instance to the foreground. Depending on how you implement each Activity, the two instances of A can get out of sync and provide a confusing experience for a user navigating back through the stack.app and other tasks. Figure 7.2: Managing tasks Or, say your Activity C can be launched from a second app with an implicit Intent. The user runs the second app, which has its own task and its own back stack. If that app uses an implicit Intent to launch your Activity C, a new instance of C is created and placed on the back stack for that second app's task. Your app still has its own task, its own back stack. 142 CU IDOL SELF LEARNING MATERIAL (SLM)

Figure 7.3: Managing tasks 2 Much of the time the Android's default behaviour for tasks works fine and you don't have to worry about how each Activity is associated with tasks, or how they exist in the back stack. If you want to change the normal behaviour, Android provides several ways to manage tasks and each Activity within those tasks, including:  Activity launches modes, to determine how an Activity should be launched.  Task affinities, which indicate which task a launched Activity belongs to. Activity Launch Modes  Use Activity launch modes to indicate how each new Activity should be treated when launched that is, if the Activity should be added to the current task, or launched into a new task. Define launch modes for theActivity with attributes on the <activity>element of theAndroidManifest.xmlfile, or with flags set on the Intent that starts that Activity. Activity Attributes  To define a launch mode for an Activity add the android launchMode attribute to the <activity> element in the AndroidManifest.xml file. This example uses a launch mode of \"standard\", which is the default.  <activity  android:name=\".SecondActivity\"  android:label=\"@string/activity2_name\"  android:parentActivityName=\".MainActivity\"  android:launchMode=\"standard\">  <!-- More attributes ... -->  </activity> 143 CU IDOL SELF LEARNING MATERIAL (SLM)

There are four launch modes available as part of the <activity> element:  \"Standard\": A new Activity is launched and added to the back stack for the current task. An Activity can be instantiated multiple times, a single task can have multiple instances of the same Activity, and multiple instances can belong to different tasks.  \"Single Top\": If an instance of an Activity exists at the top of the back stack for the current task and Intent request for that Activity arrives, Android routes that Intent to the existing Activity instance rather than creating a new instance. A new Activity is still instantiated if there is an existing Activity anywhere in the back stack other than the top.  \"Single Task\": When the Activity is launched the system creates a new task for that Activity. If another task already exists with an instance of that Activity, the system routes the Intent to that Activity instead.  \"SingleInstance\": Same as single task, except that the system doesn't launch any other Activity into the task holding the Activity instance. The Activity is always the single and only member of its task. Most apps will only use the standard or single top launch modes. See the android:launchMode attribute for more detailed information on launch modes. 7.2.2 Explicit Intents Explicit Intent in Android Although it does not look very complex through the eyes of a user, there are hundreds of operations taking place in an Android application as the user continues using it. Out of a large population, only a few curious users would know that there are tons of interactions occurring within a single Android app at a time. If you are a newly curious user looking for information on interactions within a single app, you came to the right place. The tool that enables an Android app to have its components interact with each other is called Android Intent. To put it in layman’s terms, an Android Intent is a bridge that connects Android components. With the help of an Android Intent, two app components communicate with each other. You must be wondering why app components need to communicate with each other. The reason for that is simple: A single app component cannot do everything. To be complete, an application must be able to make use of multiple components and possess the ability to transfer data from one component to the other. And this is where Android Intent comes in. An Android Intent is used when an application must request an Android component to perform an operation for it. This component can either belong to the same application or any other application present on the device. By its nature, the object of an Android Intent is a passive data structure. This PDS only holds abstract description of the required operation. In other words, the Android Intent object 144 CU IDOL SELF LEARNING MATERIAL (SLM)

carries the information that defines the requested operation. When the request is sent, the Android System uses the object’s information to select a component that canfulfil the intent. In Android, Explicit Intent is the type of Intent that explicitly defines the name of the component to be invoked by the Intent. It means that the app knows what the targeted component is and if it exists on the device or not. For this reason, Explicit Intent in Android is most used for invoking components within an application. In other words, Explicit Intent connects the internal world of an application; this is done by connecting one activity to another. Basically, an Explicit Intent in Android specifies the targeted component directly by identifying it by its package or class name. Then, the Android System only revolves the given name and launches the targeted component directly. Usually, Explicit Intent in Android is applied in an app for various reasons, such as calling a new activity or service to be launched in response to a user action and passing information from one activity to a second activity. Consider an Android calculator application page that has two text fields and a button to initiate addition. When a user fills both the text fields with numbers and clicks the button, a new page is opened that shows the result of the addition. This is an example of Explicit Intent in Android. Another example of Explicit Intent in Android can be seen on applications that require users to enter their username and password. When a user is on the login page of an app, he enters his username and password correctly and submits this information. Doing so opens a new page in the same app that displays his profile, which has his username as well. This is an example of using Explicit Intent to pass information from one activity to another. In this example, the information is the username. Important Methods of Explicit Intent in Android Now that you know what the Explicit Intent tool is and how it works in Android applications, it is time for us to move towards learning how to code this tool into our applications. Android app developers use many methods when it comes to implementing Explicit Intent in an application. Out of those methods, a few methods are very important and basic for the implementation of Explicit Intent. Here are the three most important methods used for Explicit Intent in Android.  Context startActivity This method is used for launching a new activity. It is also used for making an existing activity to perform the operation.  Context startService This method is used for starting a new service. Other than that, it is used for delivering instructions to an existence service.  Context sendBroadcast This method is used for delivering broadcast intent to broadcast receivers. 145 CU IDOL SELF LEARNING MATERIAL (SLM)

Explicit Intent in Android Steps You must be thinking that a tool like Explicit Intent with such a complex way of working is very hard to implement in an Android application. Here is the truth: It’s not hard, especially not with our tutorial to help you. In this example, we will be showing you how to make use of Explicit Intent to call a new activity to be launched in response to a user action. To start the process of coding to implement Explicit Intent in Android, you must open the Android Studio IDE first. After opening Android Studio, create a new project. The detailed method of creating a new project is discussed in our earlier tutorials. While you are creating a new project, select an appropriate name for your project. If you can’t come up with a project name, you can use the same project name as ours. We have simply used “Intent” as our project name. You will also be asked to use a suitable package name for your project. You can take our package name, which is “COM.ANDROIDAURA.EINTENT,” as an example. When you are done with creating a new project, open the MainActivity. 7.3 TOAST Toasts are transient notifications that remain visible for only a few seconds before fading out. Toasts don’t steal focus and are non-modal, so they don’t interrupt the active application. Toasts are perfect for informing your users of events without forcing them to open an Activity or read a Notification. They provide an ideal mechanism for alerting users to events occurring in background Services without interrupting foreground applications. Generally, your application should display Toasts only when one of its Activities is active. The Toast class includes a static makeText method that creates a standard Toast display window. To construct a new Toast, pass the current Context, the text message to display, and the length of time to display it (LENGTH_SHORT or LENGTH_LONG) into the makeText method. After creating a Toast, you can display it by calling show, as shown in listing 10-29. LISTING 10-29: Displaying a Toast Context = this; String MSG = “To health and happiness! INT duration = Toast LENGTH_SHORT; Toast = Toast makeText In android, Toast is a small popup notification that is used to display information about the operation which we performed in our app. The Toast will show the message for a small period, and it will disappear automatically after a timeout. Generally, the size of Toast will be adjusted based on the space required for the message and it will be displayed on the top of the main content of activity for a short period of time. 146 CU IDOL SELF LEARNING MATERIAL (SLM)

For example, some of the apps will show a message like “Press again to exit” in toast, when we pressed a back button on the home page or showing a message like “saved successfully” toast when we click on the button to save the details. Following is the pictorial representation of using Toast in android applications. Figure 7.4: TOAST Create a Toast in Android In android, we can create a Toast by instantiating an android widget Toast object using makeText method. The makeText method will take three parameters: application context, text message and the duration for the toast. We can display the Toast notification by using showmethod. Following is the syntax of creating a Toast in android applications. Toast makes Text (context, \"message\", and duration). show (). If you observe above syntax, we defined a Toast notification using makeTextmethod with three parameters, those are Parameter Description context It’s our application context. message It’s our custom message which we want to show in Toast notification. 147 CU IDOL SELF LEARNING MATERIAL (SLM)

Parameter Description duration It is used to define the duration for notification to display on the screen. Table 7.1: Toast Output of Android Toast Notification Example When we run the above example using an android virtual device (AVD) we will get a result like as shown below. Figure 7.5: Output of Android Toast Notification Example If you observe the above result, we created a toast notification and shown it on Button click based on our requirements. Change the Position of Android Toast Notification By default, the android Toast notification will always appear near the bottom of the screen, centred horizontally like as shown in the above image. In case if we want to change the position of Toast notification, we can do it by using the setGravity method. The setGravity method will accept three parameters: a Gravity constant, an x-position offset, and a y-position offset. Output of Android Toast Positioning Example When we run above example using android virtual device,we will get a result like as shown below. 148 CU IDOL SELF LEARNING MATERIAL (SLM)

Figure 7.6 Output of Android Toast Positioning If you observe the above result, we changed the position of toast notification to the top right side on Button click based on our requirements. In case if we want to change the style of toast notification, then we can do it by creating a custom XML layout file. 7.4 SPLASH SCREEN A splash screen is mostly the first screen of the app when it is opened. It is a constant screen which appears for a specific amount of time, generally shows for the first time when the app is launched. The Splash screen is used to display some basic introductory information such as the company logo, content, etc just before the app loads completely. Creating Splash screen using handler in Android Here we created two activities MainActivity showing the Splash Screen and SecondActivity in order to switch from MainActivity to SecondActivity. The main program is written in MainActivity, you can change activities as per your need.  To remove the ActionBar, you need to make following changes in your styles.xml file.  style name=\"App Theme\" parent=\"Theme App Compact light NoActionBar\"  Use colours which are suitable for your application.  No need to make any changes in your manifest file. Example: With the help of this tutorial we will cover implementation of splash screen in two scenarios. First will show splash screen using Handler and second we will not create a layout file for splash screen activity. Instead, specify activity’s theme background as splash screen layout. In the first below example we will see the use of Splash Screen using Handler class. 149 CU IDOL SELF LEARNING MATERIAL (SLM)

Below you can download code, see final output and step by step explanation of example: Figure 6.6: Splash Screen Step 1 : Create a new project and name it Splashscreen Step 2: Open res -> layout -> activity_main.xml (or) main.xml and add following code: In this step we simply added a code to display layout after Splash screen. <?xml version=\"1.0\" encoding=\"utf-8\"?> <RelativeLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:tools=\"http://schemas.android.com/tools\" android:id=\"@+id/activity_main\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" android:paddingBottom=\"@dimen/activity_vertical_margin\" android:paddingLeft=\"@dimen/activity_horizontal_margin\" android:paddingRight=\"@dimen/activity_horizontal_margin\" android:paddingTop=\"@dimen/activity_vertical_margin\" tools:context=\"abhiandroid.com.splashscreen.MainActivity\"> 150 CU IDOL SELF LEARNING MATERIAL (SLM)


Like this book? You can publish your book online for free in a few minutes!
Create your own flipbook