This document provides information about fragments in Android. It defines a fragment as a modular section of an activity that has its own lifecycle and can be reused across activities. The key points covered include:
- Fragments have their own lifecycle that is directly tied to the host activity's lifecycle.
- The fragment lifecycle involves creation, view creation, attachment/detachment from the activity, and destruction phases.
- Fragments can be added to activities either statically in XML layouts or dynamically at runtime using FragmentTransactions.
- Fragments communicate with their host activity using getActivity() and the activity can reference fragments via the FragmentManager.
The document discusses intents, broadcast receivers, and intent filters in Android. It provides examples of explicit intents that specify a component directly and implicit intents that declare an action without specifying a component. Implicit intents can be received by components that declare intent filters supporting the action, MIME type, and category. The document also discusses using intent filters in the app manifest to advertise which implicit intents an app's activities, services, and broadcast receivers can receive.
A new Linux process is started for an application with a single thread of execution. By default, all application components run in the same process and thread. Additional processes and threads can be created. The Android system tries to keep processes running as long as possible by placing them in an importance hierarchy, with foreground processes being least likely to be killed. The cached process of an inactive application is most likely to be killed first when memory is low.
This document discusses Android services and provides examples of creating different types of services. It explains that a service is an application component that can perform long-running operations in the background without a user interface. The document covers started services, which run indefinitely until stopped, and bound services, which run only as long as components are bound to them. It provides code examples for creating started services by extending the Service and IntentService classes and for creating a bound service using the Binder pattern.
Android development - Activities, Views & IntentsLope Emano
Activities provide screens for user interaction and have lifecycles to manage memory. The lifecycle involves states like active, paused, stopped which trigger callbacks like onCreate(), onStart(), onPause(). Views are UI components like TextView and occupy a rectangular area, with attributes like width, height. ViewGroups arrange views and include LinearLayout and RelativeLayout. Input events like clicks are handled via listeners. Intents launch other activities by specifying the class and optional data.
Android Classes In Mumbai
best android classes in mumbai with job assistance.
our features are:
expert guidance by it industry professionals
lowest fees of 5000
practical exposure to handle projects
well equiped lab
after course resume writing guidance
This document provides an overview of the Process class in .NET, including its properties, methods, and events. The Process class allows retrieving information about and controlling processes running on the local or remote machine. Some key points:
- Process represents a process and provides properties for ID, name, priority, memory usage, start time and more.
- Methods allow starting, stopping, waiting for exit and getting process instances by ID or name.
- Events notify when a process exits or writes to standard streams.
02 programmation mobile - android - (activity, view, fragment)TECOS
This document discusses Android activities and views. It explains that an activity represents a single screen in an app that the user can interact with. The activity lifecycle and methods like onCreate, onPause, onResume are described. Views like buttons, text fields, images are covered along with their attributes. It also discusses intents for launching activities, passing data between activities, and handling activity results.
Android is a software stack that includes an operating system, middleware and key applications for mobile devices. It uses the Java programming language and includes features like application frameworks, SQLite for storage, and support for common media formats. The Android architecture consists of applications, an application framework, libraries and services, the Android runtime and the Linux kernel. Activities are the basic building blocks of Android apps and have a defined lifecycle of states they move through as the user interacts with the app.
The document discusses intents, broadcast receivers, and intent filters in Android. It provides examples of explicit intents that specify a component directly and implicit intents that declare an action without specifying a component. Implicit intents can be received by components that declare intent filters supporting the action, MIME type, and category. The document also discusses using intent filters in the app manifest to advertise which implicit intents an app's activities, services, and broadcast receivers can receive.
A new Linux process is started for an application with a single thread of execution. By default, all application components run in the same process and thread. Additional processes and threads can be created. The Android system tries to keep processes running as long as possible by placing them in an importance hierarchy, with foreground processes being least likely to be killed. The cached process of an inactive application is most likely to be killed first when memory is low.
This document discusses Android services and provides examples of creating different types of services. It explains that a service is an application component that can perform long-running operations in the background without a user interface. The document covers started services, which run indefinitely until stopped, and bound services, which run only as long as components are bound to them. It provides code examples for creating started services by extending the Service and IntentService classes and for creating a bound service using the Binder pattern.
Android development - Activities, Views & IntentsLope Emano
Activities provide screens for user interaction and have lifecycles to manage memory. The lifecycle involves states like active, paused, stopped which trigger callbacks like onCreate(), onStart(), onPause(). Views are UI components like TextView and occupy a rectangular area, with attributes like width, height. ViewGroups arrange views and include LinearLayout and RelativeLayout. Input events like clicks are handled via listeners. Intents launch other activities by specifying the class and optional data.
Android Classes In Mumbai
best android classes in mumbai with job assistance.
our features are:
expert guidance by it industry professionals
lowest fees of 5000
practical exposure to handle projects
well equiped lab
after course resume writing guidance
This document provides an overview of the Process class in .NET, including its properties, methods, and events. The Process class allows retrieving information about and controlling processes running on the local or remote machine. Some key points:
- Process represents a process and provides properties for ID, name, priority, memory usage, start time and more.
- Methods allow starting, stopping, waiting for exit and getting process instances by ID or name.
- Events notify when a process exits or writes to standard streams.
02 programmation mobile - android - (activity, view, fragment)TECOS
This document discusses Android activities and views. It explains that an activity represents a single screen in an app that the user can interact with. The activity lifecycle and methods like onCreate, onPause, onResume are described. Views like buttons, text fields, images are covered along with their attributes. It also discusses intents for launching activities, passing data between activities, and handling activity results.
Android is a software stack that includes an operating system, middleware and key applications for mobile devices. It uses the Java programming language and includes features like application frameworks, SQLite for storage, and support for common media formats. The Android architecture consists of applications, an application framework, libraries and services, the Android runtime and the Linux kernel. Activities are the basic building blocks of Android apps and have a defined lifecycle of states they move through as the user interacts with the app.
Fragments are modular sections of an activity that have their own lifecycle and can be added or removed dynamically. Fragments are embedded within activities and use the activity's lifecycle. They allow building reusable UI components and supporting multi-pane layouts on larger screens. Fragments should be used when building multi-pane UIs or when wanting to reuse certain UI components across multiple activities. The document provides details on how to define fragments in XML layouts, add them programmatically, communicate between fragments and activities, and best practices for using fragments.
Fragments allow modularization of activities on larger screens like tablets. A fragment represents a behavior or UI portion and has its own lifecycle callbacks. Fragments can be placed in an activity layout via XML or added dynamically in code. Multiple fragments can be combined in a single activity to build a multi-pane UI. The activity lifecycle influences fragments, and fragments can be retained across configuration changes using setRetainInstance(true).
Fragments in Android allow developers to divide an activity's user interface into modular components. Fragments have their own layouts and lifecycle methods similar to activities. Developers can optimize apps for different screen sizes by dynamically adding, removing, or replacing fragments at runtime using the fragment manager. To create a fragment, developers extend the fragment class and override lifecycle methods like onCreateView() to inflate layouts.
in this presentation i will discuss fragment and how to use it to enhance your android development, also know the basics of making more than one layer in your apps
Fragments allow dividing the screen into independent portions or chunks and are used to solve tablet design problems. Fragments have their own lifecycle methods and backstack functionality to support multipane screens. Fragments depend on activities' lifecycles and cannot run without a host activity. Activities can add and remove fragments dynamically. Fragments can be created from XML, programmatically by returning a view to the activity, or without an UI. Data can be passed between fragments and activities using bundles or interfaces.
Fragments allow dividing the graphical interface of an activity into independent and reusable modules. A fragment has its own lifecycle and can be dynamically added or removed from an activity during runtime. Communication between a fragment and its activity can occur through interfaces or by accessing the activity from within the fragment. Fragments help create flexible and adaptable user interfaces for different screen sizes and configurations.
Fragments allow modular design of user interfaces on Android. They can be added dynamically at runtime to an activity. Fragments have their own lifecycle and can be reused in multiple activities. The support library provides backward compatibility for fragments on older Android versions. Best practices include using interfaces to communicate between fragments and activities, and retaining fragments across configuration changes. DialogFragments are specialized fragments for showing dialog windows.
Fragments allow modular and reusable components in an Android application. They are portions of UI for an activity that have their own lifecycle and can be added or removed during runtime. The key aspects are:
- Fragments were introduced in Android 3.0 but can be used in older versions with the compatibility library.
- Their lifecycle is directly tied to the host activity - pausing/destroying the activity also pauses/destroys fragments.
- They are defined as subclasses of Fragment and implement lifecycle methods like onCreateView to define the UI.
- Fragments can be added to activities declaratively in XML layouts or programmatically using transactions.
Fragments represent reusable portions of user interface in an activity. An activity can host multiple fragments that the user can navigate between. Fragment transactions allow adding, replacing, and removing fragments within an activity. Fragments can communicate with each other using interfaces to pass data between fragments hosted by the same activity.
[/SUMMARY]
Fragments allow modular sections to be added and removed from an activity at runtime. A fragment has its own layout and lifecycle methods similar to an activity. The document discusses how to create and manage fragments, communicate between fragments through the activity, and dynamically change the UI based on device configuration using different layouts for portrait, landscape, and larger screens. Fragments provide a flexible way to customize the user interface on different devices.
The document discusses several new features and APIs in Android 3.0 (Honeycomb) for tablets, including fragments which allow recomposing UI based on factors like screen size, loaders for asynchronously fetching content, an enhanced action bar for navigation and menus, hardware accelerated graphics, and the new holographic UI design. It also questions what some aspects of Android 3.0 may mean for future phone releases and how to detect "tablet-y" systems.
This document provides an overview of fragments and multiple layouts in Android app development. It discusses using string resources, introducing fragments, creating and adding fragments, and the fragment lifecycle. It explains that fragments allow dividing the screen into independent sections that can be reused across activities. The document demonstrates creating a main fragment class and layout, and adding the fragment to an activity's layout. It also discusses using different layouts for different screen sizes and orientations through configuration qualifiers.
This document provides an overview of best practices for Android development. It discusses topics such as UI design, including layouts and styles; using the action bar for search and progress indicators; accessibility; network connections; asynchronous tasks and services; fragments and navigation patterns; geolocation and performance; dependency injection; and recommended tools and libraries. The document provides code snippets and links to the Android developer documentation for further information on these topics.
Architecting Single Activity Applications (With or Without Fragments)Gabor Varadi
Presentation by Gabor Varadi (@zhuinden)
What Activity and Fragment actually are in Android
What are the problems they solve, and what are their downsides
How to use a custom solution that simplifies navigation in Android applications
https://github.com/Zhuinden/navigation-example
Java Svet - Communication Between Android App ComponentsAleksandar Ilić
Presentation about how to build flexible (using fragments), smooth (using async tasks and intent services) and "data up to date" (using loaders) Android applications.
Java Svet - Communication Between Android App ComponentsPSTechSerbia
Presentation about how to build flexible (using fragments), smooth (using async tasks and intent services) and "data up to date" (using loaders) Android applications.
Here are a few common ways to get/pass data from/to fragments:
1. Use arguments Bundle: Pass data to a fragment by adding it to the arguments Bundle when creating the fragment. Get data in the fragment by calling getArguments().
2. Implement listener interfaces: Define callback interfaces in the fragment and implement them in the activity. Fragment notifies activity of changes via the listener.
3. Use shared ViewModel: Define a shared ViewModel between fragments and activity. Fragments and activity can observe/update shared data in the ViewModel.
4. Direct calls to fragment methods: Activity can directly call public methods on a fragment to pass data or trigger behavior. Fragments should avoid directly accessing
This document provides an overview of key Android concepts including:
- Android's history and version timeline from 1.0 to Oreo.
- The Android activity lifecycle including methods like onCreate(), onStart(), onResume(), etc.
- What fragments are in Android and their core lifecycle methods.
- Different types of layouts that can be used in an Android app like RelativeLayout, LinearLayout, etc.
- How to integrate APIs and handle network requests and responses in an Android app.
It also provides code examples and tips for beginners on resources for learning Android development.
This document provides an overview of sensors on Android devices. It discusses categories of sensors including motion, environmental, and position sensors. It describes the Android sensor framework and types of sensors such as accelerometers, gyroscopes, gravity sensors, and rotation vectors. It provides details on accessing sensor data and best practices for using sensors. Specific sensors like temperature, humidity, and ambient light sensors are explained.
This document provides an overview of JSON and APIs for mobile programming. It defines JSON data types like numbers, strings, booleans, arrays and objects. It then explains the concept of APIs including endpoints, parameters, methods and status codes. It demonstrates making API requests from Android apps using the Volley library, including examples of GET requests without data, POST requests with data in the body, and DELETE requests with data in the URL. Code samples are provided for each type of request.
Fragments are modular sections of an activity that have their own lifecycle and can be added or removed dynamically. Fragments are embedded within activities and use the activity's lifecycle. They allow building reusable UI components and supporting multi-pane layouts on larger screens. Fragments should be used when building multi-pane UIs or when wanting to reuse certain UI components across multiple activities. The document provides details on how to define fragments in XML layouts, add them programmatically, communicate between fragments and activities, and best practices for using fragments.
Fragments allow modularization of activities on larger screens like tablets. A fragment represents a behavior or UI portion and has its own lifecycle callbacks. Fragments can be placed in an activity layout via XML or added dynamically in code. Multiple fragments can be combined in a single activity to build a multi-pane UI. The activity lifecycle influences fragments, and fragments can be retained across configuration changes using setRetainInstance(true).
Fragments in Android allow developers to divide an activity's user interface into modular components. Fragments have their own layouts and lifecycle methods similar to activities. Developers can optimize apps for different screen sizes by dynamically adding, removing, or replacing fragments at runtime using the fragment manager. To create a fragment, developers extend the fragment class and override lifecycle methods like onCreateView() to inflate layouts.
in this presentation i will discuss fragment and how to use it to enhance your android development, also know the basics of making more than one layer in your apps
Fragments allow dividing the screen into independent portions or chunks and are used to solve tablet design problems. Fragments have their own lifecycle methods and backstack functionality to support multipane screens. Fragments depend on activities' lifecycles and cannot run without a host activity. Activities can add and remove fragments dynamically. Fragments can be created from XML, programmatically by returning a view to the activity, or without an UI. Data can be passed between fragments and activities using bundles or interfaces.
Fragments allow dividing the graphical interface of an activity into independent and reusable modules. A fragment has its own lifecycle and can be dynamically added or removed from an activity during runtime. Communication between a fragment and its activity can occur through interfaces or by accessing the activity from within the fragment. Fragments help create flexible and adaptable user interfaces for different screen sizes and configurations.
Fragments allow modular design of user interfaces on Android. They can be added dynamically at runtime to an activity. Fragments have their own lifecycle and can be reused in multiple activities. The support library provides backward compatibility for fragments on older Android versions. Best practices include using interfaces to communicate between fragments and activities, and retaining fragments across configuration changes. DialogFragments are specialized fragments for showing dialog windows.
Fragments allow modular and reusable components in an Android application. They are portions of UI for an activity that have their own lifecycle and can be added or removed during runtime. The key aspects are:
- Fragments were introduced in Android 3.0 but can be used in older versions with the compatibility library.
- Their lifecycle is directly tied to the host activity - pausing/destroying the activity also pauses/destroys fragments.
- They are defined as subclasses of Fragment and implement lifecycle methods like onCreateView to define the UI.
- Fragments can be added to activities declaratively in XML layouts or programmatically using transactions.
Fragments represent reusable portions of user interface in an activity. An activity can host multiple fragments that the user can navigate between. Fragment transactions allow adding, replacing, and removing fragments within an activity. Fragments can communicate with each other using interfaces to pass data between fragments hosted by the same activity.
[/SUMMARY]
Fragments allow modular sections to be added and removed from an activity at runtime. A fragment has its own layout and lifecycle methods similar to an activity. The document discusses how to create and manage fragments, communicate between fragments through the activity, and dynamically change the UI based on device configuration using different layouts for portrait, landscape, and larger screens. Fragments provide a flexible way to customize the user interface on different devices.
The document discusses several new features and APIs in Android 3.0 (Honeycomb) for tablets, including fragments which allow recomposing UI based on factors like screen size, loaders for asynchronously fetching content, an enhanced action bar for navigation and menus, hardware accelerated graphics, and the new holographic UI design. It also questions what some aspects of Android 3.0 may mean for future phone releases and how to detect "tablet-y" systems.
This document provides an overview of fragments and multiple layouts in Android app development. It discusses using string resources, introducing fragments, creating and adding fragments, and the fragment lifecycle. It explains that fragments allow dividing the screen into independent sections that can be reused across activities. The document demonstrates creating a main fragment class and layout, and adding the fragment to an activity's layout. It also discusses using different layouts for different screen sizes and orientations through configuration qualifiers.
This document provides an overview of best practices for Android development. It discusses topics such as UI design, including layouts and styles; using the action bar for search and progress indicators; accessibility; network connections; asynchronous tasks and services; fragments and navigation patterns; geolocation and performance; dependency injection; and recommended tools and libraries. The document provides code snippets and links to the Android developer documentation for further information on these topics.
Architecting Single Activity Applications (With or Without Fragments)Gabor Varadi
Presentation by Gabor Varadi (@zhuinden)
What Activity and Fragment actually are in Android
What are the problems they solve, and what are their downsides
How to use a custom solution that simplifies navigation in Android applications
https://github.com/Zhuinden/navigation-example
Java Svet - Communication Between Android App ComponentsAleksandar Ilić
Presentation about how to build flexible (using fragments), smooth (using async tasks and intent services) and "data up to date" (using loaders) Android applications.
Java Svet - Communication Between Android App ComponentsPSTechSerbia
Presentation about how to build flexible (using fragments), smooth (using async tasks and intent services) and "data up to date" (using loaders) Android applications.
Here are a few common ways to get/pass data from/to fragments:
1. Use arguments Bundle: Pass data to a fragment by adding it to the arguments Bundle when creating the fragment. Get data in the fragment by calling getArguments().
2. Implement listener interfaces: Define callback interfaces in the fragment and implement them in the activity. Fragment notifies activity of changes via the listener.
3. Use shared ViewModel: Define a shared ViewModel between fragments and activity. Fragments and activity can observe/update shared data in the ViewModel.
4. Direct calls to fragment methods: Activity can directly call public methods on a fragment to pass data or trigger behavior. Fragments should avoid directly accessing
This document provides an overview of key Android concepts including:
- Android's history and version timeline from 1.0 to Oreo.
- The Android activity lifecycle including methods like onCreate(), onStart(), onResume(), etc.
- What fragments are in Android and their core lifecycle methods.
- Different types of layouts that can be used in an Android app like RelativeLayout, LinearLayout, etc.
- How to integrate APIs and handle network requests and responses in an Android app.
It also provides code examples and tips for beginners on resources for learning Android development.
This document provides an overview of sensors on Android devices. It discusses categories of sensors including motion, environmental, and position sensors. It describes the Android sensor framework and types of sensors such as accelerometers, gyroscopes, gravity sensors, and rotation vectors. It provides details on accessing sensor data and best practices for using sensors. Specific sensors like temperature, humidity, and ambient light sensors are explained.
This document provides an overview of JSON and APIs for mobile programming. It defines JSON data types like numbers, strings, booleans, arrays and objects. It then explains the concept of APIs including endpoints, parameters, methods and status codes. It demonstrates making API requests from Android apps using the Volley library, including examples of GET requests without data, POST requests with data in the body, and DELETE requests with data in the URL. Code samples are provided for each type of request.
This document provides summaries of various Firebase products and services, including Firebase Realtime Database, Firebase Authentication, Firebase Cloud Messaging, Firebase Notifications, Firebase Storage, Firebase Hosting, Firebase Test Lab for Android, and Firebase Crash Reporting. For each product or service, the document outlines its key capabilities and provides example use cases.
This document discusses user interface (UI) and user experience (UX) design considerations for mobile applications. It begins with an overview of simple list views and adapters in Android. It then covers several key constraints for mobile UX design, including limited data, finite battery life, hand-held usage, divided user attention, and small screens. The document provides tips for UI design on mobile, including formatting content, text size and spacing, touch controls, and hit targets. It also discusses list views and master-detail views in more detail. Overall, the document outlines important factors to consider for optimizing the mobile user experience.
The document discusses various options for storing data in Android applications, including SharedPreferences, SQLite databases, network connections, content providers, and internal/external storage. It provides details on each option, such as what type of data each is suited for and how private or public the data is. Examples are given of storing data in SharedPreferences using key-value pairs and retrieving the data. The document also covers SQLite databases and using SQL to query and manipulate structured data.
Tk2323 lecture 5 material design & recycler viewMengChun Lam
This document provides an overview of Material Design and RecyclerView for Android development. It discusses key concepts of Material Design including environment, material properties, elevation and shadows. It also outlines the steps to construct a custom list using RecyclerView, including defining data models, view holders, and an adapter to link data to views. The RecyclerView displays large data sets efficiently by maintaining a limited number of views.
This document provides an outline and overview of key concepts for working with databases and SQL in mobile programming. It discusses different types of databases like SQLite and concepts like tables, rows, columns, and basic SQL statements for creating tables, selecting, inserting, updating, and deleting data. Examples are provided for each SQL statement to demonstrate their proper syntax and usage.
This document provides an overview of user interface concepts in Android mobile app development, including:
- Common layouts like LinearLayout, RelativeLayout, and ConstraintLayout.
- Attributes for configuring views and view groups, such as width, height, padding, gravity.
- Best practices for supporting multiple screen densities and orientations using density-independent pixels and qualifiers.
- The process of declaring UI elements in XML layout files and linking them to code.
Tk2323 lecture 1 introduction to mobile applicationMengChun Lam
The document provides an introduction to a mobile application development course. It outlines topics that will be covered including Android architecture, mobile development considerations like device fragmentation and limited resources, and different app development methods like native, hybrid and web apps. It also introduces key mobile platforms like Android and iOS and how apps are distributed for each.
4. 4 What is Fragment
▹A Fragment
represents a behaviour
or a portion of user
interface in an Activity
▹You can combine
multiple fragments in
a single activity to
build a multi-pane UI
and reuse a fragment in
multiple activities
▹You can think of a
fragment as a modular
section of an activity,
which has its own
lifecycle, receives its
own input events, and
which you can add or
remove while the
activity is running
(sort of like a "sub
activity" that you can
reuse in different
5. 5 Why you need Fragment
▹Combine several
fragments in a single activity
▹Reuse the same Fragment
across different activity
▹Make better use of larger
screen space on tablets
▹Fixed/Scrolling/Swipe tab
displays
6. 6 What is Fragment
▹A fragment must
always be embedded in
an activity and the
fragment's lifecycle is
directly affected by
the host activity's
lifecycle.
▹For example, when
the activity is paused,
so are all fragments in
it, and when the
activity is destroyed, so
are all fragments.
▹However, while an
activity is running (it is
in the resumed lifecycle
state), you can
manipulate each
fragment
independently, such as
add or remove them
7. 7
Fragment
Life Cycle
▹Phase I: When a fragment gets
created, it goes through the following
states:
▸onAttach()
▸onCreate()
▸onCreateView()
▸onActivityCreated()
8. 8 Fragment Life Cycle
onAttach(Activity)
▸called once the
fragment is associated
with its activity.
onCreate(Bundle)
▸called to do initial
creation of the
fragment.
onCreateView(LayoutI
nflater, ViewGroup,
Bundle)
▸creates and returns
the view hierarchy
associated with the
fragment.
onActivityCreated(Bu
ndle)
▸tells the fragment
that its activity has
completed its own
Activity.onCreate().
10. 10 Fragment Life Cycle
onStart()
▸makes the fragment visible to
the user (based on its
containing activity being
started).
onResume()
▸makes the fragment
interacting with the user (based
on its containing activity being
resumed).
12. 12 Fragment Life Cycle
onPause()
▸fragment is no longer
interacting with the user either
because its activity is being
paused or a fragment operation
is modifying it in the activity.
onStop()
▸fragment is no longer visible
to the user either because its
activity is being stopped or a
fragment operation is modifying
it in the activity.
13. 13
Fragment
Life Cycle
▹Phase IV: When the
fragment is destroyed, it
goes through the
following states:
▸onPaused()
▸onStop()
▸onDestroyView()
▸onDestroy()
▸onDetach()
14. 14 Fragment Life Cycle
onDestroyView()
▸allows the fragment
to clean up resources
associated with its
View.
onDestroy()
▸called to do final
cleanup of the
fragment's state.
onDetach()
▸ called immediately
prior to the fragment
no longer being
associated with its
activity.
19. 19
Element to create the
Fragment
▹To create a fragment, extend the Fragment class, then
override key lifecycle methods to insert your app logic,
similar to the way you would with an Activity class.
20. 20
Add
Fragment in
activity_main
layout file
Create a class that
extends Fragment
Create a xml layout
file contain the
appearance
Use the
onCreateView to link
its appearance (view
that contains
fragment tag)
26. 26
Create a class that extend
Fragment: Inflater.inflate
https://www.bignerdranch.com/blog/understanding-androids-layoutinflater-inflate/
public boolean onCreateOptionsMenu(Menu menu) {
//it is a "tool" that generate the UI from the menu
resources
MenuInflater inflater = getMenuInflater();
//define which menu wanted to generated
inflater.inflate(R.menu.menu_main,menu);
return true;
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_detail, container, false);
tv_matrix = (TextView) view.findViewById(R.id.fragment_detail_matrix);
tv_name = (TextView) view.findViewById(R.id.fragment_detail_name);
return view;
}
• LayoutInflater
• which coverts an XML layout file into corresponding
ViewGroups and Widgets
27. 27
Show the fragment in the
main UI
▹Xml layout
▸Static
▹Add a Fragment to an Activity at Runtime
▸dynamic
34. 34
Add a Fragment to an
Activity at Runtime
▹Rather than defining the fragments for an activity in the
layout file
▹as shown in the previous lesson with
the<fragment> element
▹you can add a fragment to the activity during the activity
runtime. This is necessary if you plan to change fragments
during the life of the activity.
35. 35
Add a Fragment to an
Activity at Runtime
▹To perform a transaction such as add or remove a
fragment,
▹you must use the FragmentManager to create a
FragmentTransaction, which provides APIs to add, remove,
replace, and perform other fragment transactions.
36. 36
Add a Fragment to an
Activity at Runtime
▹If your activity allows the fragments to be removed and
replaced, you should add the initial fragment(s) to the
activity during the activity's onCreate() method
▹An important rule when dealing with fragments—
especially when adding fragments at runtime—is that your
activity layout must include a fragment container View in
which you can insert the fragment.
37. 37
Add a
Fragment to
an Activity at
Runtime
Create a xml layout file
contain the appearance
Create a class that
extends Fragment
Use the onCreateView to
link its appearance
Prepare a view container
for the fragment
Get a reference to
FragmentManager
Begin the transaction by
calling the
beginTransaction()
Use Transaction.add(int
containerViewId,
Fragment fragment,
String tag) to add a
fragment to the activity
state.
Transaction.commit() to
finish it
39. 39
Create a Fragment with the
class extends Fragment
import android.support.v4.app.Fragment;
40. 40
Prepare a view container for
the fragment
<LinearLayout
android:orientation="vertical"
android:id="@+id/fragmentContainer"
android:layout_width="300dp"
android:layout_height="150dp"
app:layout_constraintRight_toRightOf="@+id/fragment3"
app:layout_constraintLeft_toLeftOf="@+id/fragment3"
android:layout_marginTop="32dp"
app:layout_constraintTop_toBottomOf="@+id/textView">
</LinearLayout>
41. 41
FragmentTransaction fragmentTransaction ;
fragmentManager = getSupportFragmentManager();
btnFragA.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.add(R.id.fragmentContainer,fragmentA);
fragmentTransaction.commit();
}
});
}
Add a Fragment to an Activity at
Runtime –InsideMainActivity.java
42. 42
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
MyFragmentA fragmentA = new MyFragmentA();
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.add(R.id.fragmentContainer,fragmentA);
fragmentTransaction.commit();
}
Add a Fragment to an Activity at
Runtime –InsideMainActivity.java
48. 48
Communicating with the
Activity
▹Although a Fragment is implemented as an object that's
independent from an Activity and can be used inside
multiple activities, a given instance of a fragment is directly
tied to the activity that contains it.
▹Specifically, the fragment can access the Activity instance
with getActivity() and easily perform tasks such as find a
view in the activity layout:
▹View listView = getActivity().findViewById(R.id.list);
49. 49
Communicating with the
Activity
▹Likewise, your activity can call methods in the fragment by
acquiring a reference to the Fragment from
FragmentManager, using
▸findFragmentById() for fragments that provide a UI in
the activity layout
▸findFragmentByTag(). for fragments that do or don't
provide a UI.
51. 51
public interface OnFragmentInteractionListener {
// TODO: Update argument type and name
void sendData(String matrix, String name);
}
ListFragment
btt_send.setOnClickListener(new View.OnClickListener()
{
@Override
sendData(mMatrixNo, mName);
});
public class MainActivity extends AppCompatActivity
implements ListFragment.OnFragmentInteractionListener
{
MainActivity
@Override
public void sendData(String matrix, String name) {
/* pass the data to detail Fragment using Bundle
commit the fragment transaction*/
Bundle args = new Bundle();
args.putString(DetailFragment.EXTRA_MATRIX, matrix);
args.putString(DetailFragment.EXTRA_NAME, name);
myDetailFragment.setArguments(args);
DetailFragment
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_detail, container,
false);
tv_matrix = (TextView) view.findViewById(R.id.fragment_detail_matrix);
tv_name = (TextView) view.findViewById(R.id.fragment_detail_name);
Bundle bundle = getArguments();
if (bundle != null) {
tv_matrix.setText(bundle.getString(EXTRA_MATRIX));
tv_name.setText(bundle.getString(EXTRA_NAME));
}
return view;
}
Communicating with
Fragment
52. 52
ListFragment
• interface OnFragmentInteractionListener
• sendData(mMatrix, mName);
MainActivity
• implements ListFragment.OnFragmentInteractionListener
• Override sendData(String matrix, String name);
• Set the data using bundle and pass it to the DetailFragment
DetailFragment
• public View onCreateView(LayoutInflater inflater, ViewGroup
container,
Bundle savedInstanceState)
• Check is there data inside Bundle
Communicating with Fragment -
Flow
53. 53 Android Material Design
▹Material design is a comprehensive guide for visual, motion, and
interaction design across platforms and devices.
▹Android now includes support for material design apps.
▹Android 5.0 (Lollipop)
▸November 3, 2014
▹Android Design Support Library
▸29 MAY 2015
▸24 February 2016
53
55. 55
Add
Fragment in
activity_main
layout file
Modify the theme
• Remove action bar feature
Create Fragment UI (XML)
Create fragment with
class (Java)
Create a Main UI with
(XML)
• Coordinate Layout
• AppBarLayout
• Toolbar
• TabLayout
• ViewPager
Create
FragmentPagerAdapter
(Java)
Setup the View (Java)
• Toolbar
• TabLayout
• ViewPager
60. 60
AppBarLayout/ToolBar/
TabLayout
▹AppBarLayout is a vertical LinearLayout which implements many of
the features of material designs app bar concept, namely scrolling
gestures.
▹This view depends heavily on being used as a direct child within a
CoordinatorLayout.
▹If you use AppBarLayout within a different ViewGroup, most of it's
functionality will not work.
▹ToolBar
▹TabLayout provides a horizontal layout to display tabs.
62. 62 ViewPager
▹Layout manager that
allows the user to flip
left and right through
pages of data. You
supply an
implementation of a
PagerAdapter to
generate the pages that
the view shows.
▹You can create swipe
views in your app using
the ViewPager widget,
available in the
Support Library.
▹The ViewPager is a
layout widget in which
each child view is a
separate page (a
separate tab) in the
layout.
<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.view.ViewPager
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/pager"
android:layout_width="match_parent"
android:layout_height="match_parent" />
64. 64 PagerAdapter
▹To insert child views that represent each page, you need to hook this
layout to a PagerAdapter. There are two kinds of adapter you can use:
▹FragmentPagerAdapter
▸This is best when navigating between sibling screens representing
a fixed, small number of pages.
▹FragmentStatePagerAdapter
▸This is best for paging across a collection of objects for which the
number of pages is undetermined.
▸It destroys fragments as the user navigates to other pages,
minimizing memory usage.
65. 65 FragmentPagerAdapter
getCount()
▸Return the number of
views available.
getItem(int position)
▸Return the Fragment
associated with a
specified position
getPageTitle(int
position)
▸This method may be
called by the ViewPager to
obtain a title string to
describe the specified page.
66. 66
Change Tabs with Swipe
Views: Monitor Tab Changes
tabLayout.setOnTabSelectedListener(new OnTabSelectedListener()
• onTabReselected(Tab tab)
• Called when a tab that is already selected is chosen again by the
user.
• onTabSelected(Tab tab)
• Called when a tab enters the selected state.
• onTabUnselected(Tab tab,)
• Called when a tab exits the selected state.
67. 67
Step 1: Add the appcompat and
design support library to the
workspce
dependencies {
compile fileTree(include: ['*.jar'], dir: 'libs')
testCompile 'junit:junit:4.12'
compile 'com.android.support:appcompat-v7:24.2.0'
compile 'com.android.support:design:24.2.0'
}
68. 68
Step 2: Remove the
actionbar from the theme
<!-- Base application theme. -->
<style name="AppTheme"
parent="Theme.AppCompat.Light.NoActionBar">
<!-- Customize your theme here. -->
<item name="colorPrimary">@color/colorPrimary</item>
<item name="colorPrimaryDark">@color/colorPrimaryDark</item>
<item name="colorAccent">@color/colorAccent</item>
</style>
74. Step 5: Extend and
Implement the
FragmentPagerAdapte
r method
75. 75
Extend and Implement the
FragmentPagerAdapter
method
public class TabViewPagerAdapter extends FragmentPagerAdapter{
//for storing the fragment and the title
private final List<Fragment> mFragmentList = new ArrayList<>();
private final List<String> mFragmenTitletList = new ArrayList<>();
public TabViewPagerAdapter(FragmentManager fm) {
super(fm);
// TODO Auto-generated constructor stub
}
public void addFrag(Fragment fragment, String title)
{
mFragmentList.add(fragment);
mFragmenTitletList.add(title);
}
76. 76
Extend and Implement the
FragmentPagerAdapter
method
@Override
public Fragment getItem(int position) {
// Get the fragment
return mFragmentList.get(position);
}
@Override
public int getCount() {
// How many fragment you want to show
return mFragmentList.size();
}
@Override
public CharSequence getPageTitle(int position) {
// The title of the tab
return mFragmenTitletList.get(position);
}
77. Step 7: Link all the
view in the
mainactivity.java
82. 82
private final List<Fragment> mFragmentList = new
ArrayList<>();
private final List<String> mFragmentTitleList =
new ArrayList<>();
public TabViewPagerAdapter(FragmentManager fm) {
super(fm);
}
@Override
public Fragment getItem(int position) {
return mFragmentList.get(position);
}
@Override
public CharSequence getPageTitle(int position) {
return mFragmentTitleList.get(position);
}
@Override
public int getCount() {
return mFragmentList.size();
}
public void addFrag(Fragment fragment, String
title)
{
mFragmentList.add(fragment);
mFragmentTitleList.add(title);
}
TabViewPagerAdapter
private void setupViewPager(ViewPager viewPager) {
TabViewPagerAdapter adapter = new
TabViewPagerAdapter(getSupportFragmentManager());
adapter.addFrag(new FragmentA(), "Tab A");
adapter.addFrag(new FragmentB(), "Tab B");
adapter.addFrag(new FragmentC(), "Tab C");
viewPager.setAdapter(adapter);
}
MainActivity
83. 83
Setup TabLayout by pass the
viewpager to the TabLayout
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
.
.
.
//create the viewPager with Fragment and pass it to
the adapter
setupViewPager(viewPager);
//setup the viewPager with the tab navigation
tabLayout.setupWithViewPager(viewPager);
setupToolbar();
84. 84 Setup Toolbar
//get the toolbar from the xml file
Toolbar toolbar = (Toolbar) findViewById(R.id.main_toolbar);
// tell the "AppCompatActivity" use this toolbar
setSupportActionBar(toolbar);
85. 85
Implements the TabListener
Method
tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
@Override
public void onTabSelected(TabLayout.Tab tab) {
switch (tab.getPosition()) {
case 0:
Toast.makeText(getApplicationContext(), "Fragment A is selected",
Toast.LENGTH_SHORT).show();
break;
case 1:
Toast.makeText(getApplicationContext(), "Fragment B is selected",
Toast.LENGTH_SHORT).show();
break;
case 2:
Toast.makeText(getApplicationContext(), "Fragment C is selected",
Toast.LENGTH_SHORT).show();
break;
}
}
86. 86
▹Test your app, You
should able to change
the fragment by
selecting the Tab and
also dragging the
fragment
87. Navigation Drawer Old
& New (Optional)
https://www.google.com/design/spec/patterns/navigation-
drawer.html#navigation-drawer-behavior
http://wear.techbrood.com/design/patterns/navigation-drawer.html
88. 88 What is Navigation Drawer
▹The navigation drawer is a
panel that transitions in from
the left edge of the screen and
displays the app’s main
navigation options.
▹The user can bring the
navigation drawer onto the
screen by swiping from the left
edge of the screen or by
touching the application icon
on the action bar.
89. 89
What is
Navigation
Drawer
▹The nav drawer spans the full height of the screen, including
behind the status bar, at a resting elevation of 16dp. Everything
behind the drawer is still visible but darkened by a scrim.
90. 90 Navigation Hubs
▹The navigation drawer is a reflection of your app’s structure and displays
its major navigation hubs.
▹Think of navigation hubs as those places in your app that a user will want
to visit frequently or use as a jumping-off point to other parts of the app. At a
minimum, the navigation hubs are the top-level views, since they
correspond to your app’s major functional areas.
▹If your app’s structure is deep, you can add screens from lower levels that
your users will likely visit often and make those navigation hubs as well.
▹The navigation drawer contains all of your app's navigation hubs. Include
your top level screens as well as important lower-level screens.
92. 92
Dismissing Navigation
Drawer
▹When the navigation drawer is expanded, the user can
dismiss it in one of four ways:
▸Touching the content outside the navigation drawer
▸Swiping to the left anywhere on the screen (including
edge swipe from right)
▸Touching the app icon/title in the action bar
▸Pressing Back
93. 93
When to Use the Navigation
Drawer
▹More than 3 top-level views
▸Navigation drawers are great for displaying a large
number of navigation targets concurrently. Use the
navigation drawer if you have more than 3 unique top-
level views. If not, use fixed tabs for top-level
organization to ease discovery and interaction.
94. 94
When to Use the Navigation
Drawer
▹Cross-navigation from lower levels
▸If your app requires cross-navigating between lower-
level screens, consider using the navigation drawer.
Because it is accessible from anywhere in the app, the
drawer enables efficient navigation from lower-level
screens to other important places in your app.
96. 96
When to Use the Navigation
Drawer
▹Deep navigation branches
▸If you have particularly deep branches, navigating to
the top-level of your app can become repetitive and
cumbersome with Up and Back alone. Since navigation
drawers are accessible from anywhere in the app,
navigation up to the top level is faster and more efficient.
98. 98
Content of the Navigation
Drawer
▹Keep the content of the navigation drawer focused on app navigation.
Expose the navigation hubs of your app as list items inside the
navigation drawer - one item per row
▹Titles, icons, and counters
▸You can structure navigation targets by adding titles. The titles are
not interactive, but just organize navigation targets into functional
topics. If you have many navigation targets, use titles to orient the
user within the drawer.
▸Navigation targets can have optional leading icons as well as
trailing counters. Use the counters to inform users about a changed
state of data in the corresponding view.
99. 99
▹Navigation targets can
have optional leading
icons as well as trailing
counters. Use the
counters to inform users
about a changed state
of data in the
corresponding view
101. 101 Interaction
▹Introduce the user to the drawer at first use
▸Upon first launch of your app, introduce the user to the navigation
drawer by automatically opening it.
▹Give the user a quick peek
▸If the user touches the very left edge of the screen (within 20 dp
from the left), have the drawer peek out as soon as the finger makes
contact with the display. This promotes accidental discovery and
provides richer feedback.
▹Highlights
▸When you open the navigation drawer from a screen that is
represented inside the drawer, highlight its entry in the drawer.
103. 103 Interaction
▹System Back at the top level of the app
▸Touching System Back at the app’s top level never opens the navigation
drawer. Instead, System Back behaves according to the navigation rules for
the top level, such as navigating to the previous app within the task or
navigating to the Home screen
104. 104 Interaction
▹System Back at the top level of the app
▸If the user navigates to a lower hierarchy screen from the navigation
drawer and the screen has a direct parent, then the Back stack is reset and
Back points to the target screen’s parent. This Back behavior is the same as
when a user navigates into an app from a notification