Presentation is loading. Please wait.

Presentation is loading. Please wait.

Activities and Fragments

Similar presentations


Presentation on theme: "Activities and Fragments"— Presentation transcript:

1 Activities and Fragments
CS 240 – Advanced Programming Concepts

2 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

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

4 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

5 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)

6 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)

7 onSaveInstanceState(Bundle)
Additional Info:

8 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

9 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

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

11 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);

12 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

13 Returning Results from an Activity
Calling activity calls startActivityForResult(Intent) instead of startActivity(Intent) See GeoQuiz/QuizActivity (lines ) 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(…)

14 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

15 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

16 Android Fragments

17 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

18 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(…)

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

20 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

21 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; }

22 Inflate View in onCreateView(…)
Fragments inflate their view in onCreateView(…) @Override public View 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; }

23 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

24 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)

25 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


Download ppt "Activities and Fragments"

Similar presentations


Ads by Google