Activities and Fragments

Slides:



Advertisements
Similar presentations
Programming with Android: Android for Tablets Luca Bedogni Marco Di Felice Dipartimento di Scienze dellInformazione Università di Bologna.
Advertisements

Programming with Android: Android for Tablets Luca Bedogni Marco Di Felice Dipartimento di Scienze dell’Informazione Università di Bologna.
Programming with Android: Activities
Android 02: Activities David Meredith
All About Android Introduction to Android 1. Creating a New App “These aren’t the droids we’re looking for.” Obi-wan Kenobi 1. Bring up Eclipse. 2. Click.
The Android Activity Lifecycle. Slide 2 Introduction Working with the Android logging system Rotation and multiple layouts Understanding the Android activity.
Manifest File, Intents, and Multiple Activities. Manifest File.
The Activity Class 1.  One application component type  Provides a visual interface for a single screen  Typically supports one thing a user can do,
More on User Interface Android Applications. Layouts Linear Layout Relative Layout Table Layout Grid View Tab Layout List View.
Cosc 4730 Android TabActivity and ListView. TabActivity A TabActivity allows for multiple “tabs”. – Each Tab is it’s own activity and the “root” activity.
Programming with Android: Android Fragments Luca Bedogni Marco Di Felice Dipartimento di Scienze dell’Informazione Università di Bologna.
Chien-Chung Shen Manifest and Activity Chien-Chung Shen
CS378 - Mobile Computing Anatomy of an Android App and the App Lifecycle.
ANDROID UI – FRAGMENTS. Fragment  An activity is a container for views  When you have a larger screen device than a phone –like a tablet it can look.
Android Mobile computing for the rest of us.* *Prepare to be sued by Apple.
Mobile Programming Lecture 6
Copyright© Jeffrey Jongko, Ateneo de Manila University Of Activities, Intents and Applications.
Understand applications and their components activity service broadcast receiver content provider intent AndroidManifest.xml.
Android – Fragments L. Grewe.
Mobile Programming Lecture 5 Composite Views, Activities, Intents and Filters.
Cosc 4730 Android Fragments. Fragments You can think of a fragment as a modular section of an activity, which has its own lifecycle, receives its own.
Noname. Conceptual Parts States of Activities Active Pause Stop Inactive.
Mobile Programming Midterm Review
Applications with Multiple Activities. Most applications will have more than one activity. The main activity is started when the application is started.
Working with Multiple Activities. Slide 2 Introduction Working with multiple activities Creating multiple views Introduction to intents Passing data to.
Android Application Lifecycle and Menus
Class on Fragments & threads. Fragments fragment is a modular section of an activity, which has its own lifecycle, receives its own input events, and.
Activities and Intents Chapter 3 1. Objectives Explore an activity’s lifecycle Learn about saving and restoring an activity Understand intents and how.
CHAPTER 4 Fragments ActionBar Menus. Explore how to build applications that use an ActionBar and Fragments Understand the Fragment lifecycle Learn to.
School of Engineering and Information and Communication Technology KIT305/KIT607 Mobile Application Development Android OS –Permissions (cont.), Fragments,
Android Fragments. Slide 2 Lecture Overview Getting resources and configuration information Conceptualizing the Back Stack Introduction to fragments.
Working with Multiple Activities. Slide 2 Introduction Working with multiple activities Putting together the AndroidManifest.xml file Creating multiple.
Lab7 – Appendix.
Introduction to android
Concurrency in Android
Activity and Fragment.
Adapting to Display Orientation
CS240: Advanced Programming Concepts
Android – Event Handling
Activities, Fragments, and Events
Fragment ?.
Fragments: Introduction
CS499 – Mobile Application Development
Mobile Application Development BSCS-7 Lecture # 6
Activities and Intents
Android Activities An application can have one or more activities, where Each activity Represents a screen that an app present to its user Extends the.
Anatomy of an Android App and the App Lifecycle
Widgets & Fragments Kalin Kadiev Astea Solutions AD.
The Android Activity Lifecycle
Android – Fragments L. Grewe.
ANDROID UI – FRAGMENTS UNIT II.
Android Application Development android.cs.uchicago.edu
CIS 470 Mobile App Development
Chapter 9: Fragments.
CIS 470 Mobile App Development
Anatomy of an Android App and the App Lifecycle
Activity Lifecycle Fall 2012 CS2302: Programming Principles.
Activities and Intents
Activities and Intents
HNDIT2417 Mobile Application Development
CIS 470 Mobile App Development
Activities and Intents
CIS 470 Mobile App Development
Objects First with Java
Activities and Intents
SE4S701 Mobile Application Development
CS 240 – Advanced Programming Concepts
Activities, Fragments, and Intents
Android Sensor Programming
CIS 694/EEC 693 Android Sensor Programming
Presentation transcript:

Activities and Fragments CS 240 – Advanced Programming Concepts

Activities Represent the screens in your Android application Divided into two pieces: The UI layout (normally defined in an xml file with a combination of regular widgets (views) and ViewGroups (containers for other views) The ActivityXXX.java file is where you select and inflate the view for the activity and put your event handling code for the activity and it’s view objects. Layouts are reusable

Qualified Layouts Can have separate layouts for different orientations (portrait vs landscape) different screen heights and widths, etc. Example: GeoQuiz/QuizActivity

The Activity Lifecycle Activities have a lifecycle, controlled by the Android system Things that cause lifecycle/activity state changes: Creation of a new activity Activation (manually or programmatically) of an activity that wasn’t active before Rotation of the device Interruptions from other apps (i.e. phone calls) Low memory Other

The Six Main Activity Callbacks protected void onCreate(Bundle savedInstanceState) When the system first creates the activity (set the UI/content view here) protected void onStart() Makes the activity visible to the user (usually no need to implement) protected void onResume() Activity is in the foreground and ready for the user to interact with it protected void onPause() First indication that the user is leaving the activity. It is no longer in the foreground. protected void onStop() Activity is no longer visible to the user protected void onDestroy() Activity is about to be destroyed (either because it is finished or there was a configuration change—most commonly a rotation of the device)

Additional Callbacks protected void onRestart() Called if the activity was stopped but not destroyed, and is now being restarted The activity was not active but is about to become active onStart() will be called next protected void onSaveInstanceState(Bundle savedInstanceState) Called between onPause() and onStop() Provides an opportunity to save state so it can be restored after a configuration change (i.e. rotation)

onSaveInstanceState(Bundle) Additional Info: https://developer.android.com/guide/components/activities/activity-lifecycle

Activity Lifecycle Demo GeoQuiz Set logcat to “Debug” and filter on “QuizActivity” Observe the output for the following changes Initial creation Rotation Use of ”recents” button to make another app active Use of “home” button Use of “back” button

Saving and Restoring Instance State Use the onSaveInstanceState(Bundle) callback to save state in an activity record before it is lost due to a configuration or other short-term change Doesn’t work for long-term storage (activity records are removed when the user hits the ‘back’ button, when an activity is destroyed, when the device is rebooted, or when the activity hasn’t been used for a while) Default (inherited) implementation saves state for all UI components. Doesn’t save state for instance variables. Use the Bundle passed to onCreate(Bundle) to restore state Be sure to check for a null bundle. If it’s null, there’s no saved state to restore. Example GeoQuiz/QuizActivity.java

Starting An Activity Start an activity (from another activity) by creating an instance of the Intent class and passing it to the startActivity(Intent) method startActivity(Intent) is defined in the Activity class Example: Intent intent = new Intent(QuizActivity.this, CheatActivity.class); startActivity(intent); We usually create intents from an inner class event handler, so this is a reference to the containing activity. The activity we want to start.

Starting an Activity and Passing Data boolean answerIsTrue = mQuestionBank[mCurrentIndex].isAnswerTrue(); Intent intent = new Intent(QuizActivity.this, CheatActivity.class); intent.putExtra(EXTRA_ANSWER_IS_TRUE, answerIsTrue); intent.putExtra(EXTRA_CHEATS_REMAINING, cheatsRemaining); startActivity(intent);

Retrieving Data from an Intent Intent intent = getIntent(); boolean isAnswerTrue = intent.getBooleanExtra(EXTRA_ANSWER_IS_TRUE); This would be available to the activity that was called

Returning Results from an Activity Calling activity calls startActivityForResult(Intent) instead of startActivity(Intent) See GeoQuiz/QuizActivity (lines 105-110) Called activity creates an Intent, puts result data in the intent as intent extras (if needed), and calls setResult setResult(int resultCode) setResult(int resultCode, Intent data) See GeoQuiz/CheatActivity.setResult(…) Calling activity provides an onActivityResult(…) callback method See GeoQuiz/QuizActivity.onActivityResult(…)

Applications to Family Map Client Main Activity (MapFragment) PersonActivity is started when event info is clicked (person or personId is passed as intent extra) Search, Filter, and Settings activities are started when the menu items are clicked Depending on how you implement them, Settings and Filter activities may return results indicating any changes made by the user PersonActivity Clicking a person starts another PersonActivity with the Person or personId passed as an intent extra Clicking an event starts an EventActivity with the Event or eventId passed as an intent extra

Applications to Family Map Client SearchActivity Clicking a person starts a PersonActivity with the Person or personId passed as an intent extra Clicking an event starts an EventActivity with the Event or eventId passed as an intent extra SettingsActivity Re-sync data and Logout go back to MainActivity

Android Fragments

Fragments Reusable pieces of UI Layouts are already reusable, but fragments allow you to reuse the entire UI (including event handlers, etc.) Must be hosted by (displayed in) Activities Placed inside a FrameLayout Use the FragmentManager class to place a fragment in a FrameLayout of an Activity

The Fragment Lifecycle Fragments have a lifecycle similar to activities Restore saved instance state in onCreate(Bundle) or onCreateView(Bundle) Save instance sate in onSaveInstanceState(Bundle) (same as Activity) Inflate the view in onCreateView(…)

https://developer.android.com/guide/components/fragments onSaveInstanceState(Bundle) Additional Info: https://developer.android.com/guide/components/fragments

Create a Fragment in an Activity @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_order_info); ... FragmentManager fm = this.getSupportFragmentManager(); shippingAddressFragment = (AddressFragment) fm.findFragmentById(R.id.shippingFrameLayout); if (shippingAddressFragment == null) { shippingAddressFragment = createAddressFragment(getString(R.string.shippingAddressTitle)); fm.beginTransaction() .add(R.id.shippingFrameLayout, shippingAddressFragment) .commit(); } Above code is in the hosting activity R.id.shippingFrameLayout is a FrameLayout in R.layout.activity_order_info Example: FragmentExample/OrderInfoActivity.java

Create a Fragment in an Activity private AddressFragment createAddressFragment(String title) { AddressFragment fragment = new AddressFragment(); Bundle args = new Bundle(); args.putString(AddressFragment.ARG_TITLE, title); fragment.setArguments(args); return fragment; }

Inflate View in onCreateView(…) Fragments inflate their view in onCreateView(…) @Override public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_address, container, false); TextView titleTextView = view.findViewById(R.id.titleTextView); titleTextView.setText(title); streetEditText = view.findViewById(R.id.streetEditText); cityEditText = view.findViewById(R.id.cityEditText); stateEditText = view.findViewById(R.id.stateEditText); zipCodeEditText = view.findViewById(R.id.zipCodeEditText); return view; }

Passing Data to a Fragment Fragments shouldn’t depend on a specific activity, so they shouldn’t access their hosting fragment’s data directly Two main steps to pass data to a fragment: Pass an intent extra when starting the hosting activity The hosting activity passes the data to the fragment when it creates the fragment

Passing Data to a Fragment Example (CriminalIntent-Chapt10) Pass an intent extra when starting the hosting activity CrimeActivity.createFragment() SingleFragmentActivity.onCreate(Bundle) The hosting activity retrieves the data from it’s intent The hosting activity stashes the data in a Bundle, creates the fragment and attaches the bundle to the fragment CrimeActivity.creatFragment() The fragment retrieves the data from it’s arguments bundle CrimeFragment.onCreate(Bundle)

Applications to Family Map Client MainActivity.onCreate(…) Add LoginFragment if user not logged in Add MapFragment if user is logged in MainActivity (login success) Replace LoginFragment with MapFragment EventActivity.onCreate(…) Activity receives Event or EventId as intent extra Activity creates MapFragment and passes Event or EventId as argument Add MapFragment