SlideShare a Scribd company logo
Fragment
TK2323 Mobile Programming
Sem 1 2017/2018
Lam Meng Chun
lammc@ukm.edu.my (H-04-10)
2 Outline
Navigation Drawer
(Optional)
2
Fragment
▹ Fragment Lifecycle
▹ Fragment Creation
▹ Static and dynamic
way
Tab Layout
▹ Tab ViewPager
▹ FragmentPagerAdapter
Fragment
3
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 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 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
Fragment
Life Cycle
▹Phase I: When a fragment gets
created, it goes through the following
states:
▸onAttach()
▸onCreate()
▸onCreateView()
▸onActivityCreated()
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().
9
Fragment
Life Cycle
▹Phase II: When the
fragment becomes
visible, it goes through
these states:
▸onStart()
▸onResume()
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).
11
Fragment
Life Cycle
▹Phase III: When the
fragment goes into the
background mode, it
goes through these
states:
▸onPaused()
▸onStop()
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
Fragment
Life Cycle
▹Phase IV: When the
fragment is destroyed, it
goes through the
following states:
▸onPaused()
▸onStop()
▸onDestroyView()
▸onDestroy()
▸onDetach()
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.
15
Fragment
Life Cycle
16
Fragment’s
Life Cycle
17
Fragment’s
Life Cycle
Complete Fragment’s LifeCycle https://github.com/xxv/android-lifecycle
Ready the Fragment
18
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
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)
21
Create the
Fragment
XML Layout
file
22
Create a class
that extend
Fragment
23
Create a class
that extend
Fragment…
24
Create a class
that extend
Fragment…
25
Create a class
that extend
Fragment:
Override the
onCreateView
method
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
Show the fragment in the
main UI
▹Xml layout
▸Static
▹Add a Fragment to an Activity at Runtime
▸dynamic
Fragment
XML Layout - Static
29
Add
Fragment in
activity_main
layout file
30
Add
Fragment in
activity_main
layout file
31
Add Fragment in
activity_main layout file
<fragment
android:layout_width="300dp"
android:name="com.tk2323.ftsm.fragment_test.MyFragmentA"
android:id="@+id/fragment3"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
android:layout_height="150dp"
android:layout_marginTop="16dp"
app:layout_constraintTop_toBottomOf="@+id/editText2" />
32 Output
Add a Fragment to an
Activity at Runtime
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
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
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
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
38 Output
39
Create a Fragment with the
class extends Fragment
import android.support.v4.app.Fragment;
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
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
@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
43 Output
44 Add Frag A
btnFragA.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
fragmentTransaction = fragmentManager.______;
fragmentTransaction.______(R.id.fragmentContainer,fragmentA);
fragmentTransaction._______;
}
});
45 Replace with Fragment B
btnFragA.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
fragmentTransaction = fragmentManager._______;
fragmentTransaction.______(R.id.fragmentContainer,______);
fragmentTransaction._______;
}
});
46 Remove Fragment B
btnFragA.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.______(______);
fragmentTransaction._______;
}
});
Communicating with
the Activity
(Optional)
47
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
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.
50
Communicating with the
Activity
▹For example:
▸MyFragmentA fragment = (MyFragmentA)
getFragmentManager().findFragmentById(R.id.example_f
ragment);
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
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 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
54
Tab Navigation
Scrollable Tabs
Swipe Tabs
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
56
57
Main UI
58
Coordinate
Layout
▹The Design library
introduces
CoordinatorLayout, a
layout which provides an
additional level of control
over touch events
between child views
▹Example of this is when
you add a
▸FloatingActionButton
▸Snackbar.make()
▸Collapsed Toolbar
59
Coordinate
Layout
<!-- CoordinatorLayout -->
<android.support.design.widget.CoordinatorLayout
xmlns:android="http://schemas.android.com/apk/res/andro
id"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent" >
</android.support.design.widget.CoordinatorLayout>
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.
61
AppBarLayou
t/ToolBar/
TabLayout
<android.support.design.widget.AppBarLayout
android:id="@+id/main_appbar"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<android.support.v7.widget.Toolbar
android:id="@+id/main_toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
app:layout_scrollFlags="scroll|enterAlways"
android:background="?attr/colorPrimary" />
<android.support.design.widget.TabLayout
android:id="@+id/main_tabs"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</android.support.design.widget.AppBarLayout>
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" />
63
ViewPager
<?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 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 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
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
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
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>
Step 3: Prepare the
XML Layout and
Fragment Class
70
Create the Fragment XML
Layout file
71
Create a class that extend
Fragment
72
Add Fragment in
activity_main layout file
import android.support.v4.app.Fragment;
73
Step 4:
Prepare the
Main UI
Layout Class
Step 5: Extend and
Implement the
FragmentPagerAdapte
r method
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
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);
}
Step 7: Link all the
view in the
mainactivity.java
78
Toolbar toolbar;
TabLayout tabLayout;
ViewPager viewPager;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
toolbar = (Toolbar) findViewById(R.id.main_toolbar);
tabLayout = (TabLayout) findViewById(R.id.main_tabs);
viewPager = (ViewPager) findViewById(R.id.main_viewpager);
}
Step 8: Setup all the
view
80
Data
Source
Adapter
(FragmentPa
gerAdapter)
Adapter View
ViewPager
Bridge
• Adapters in Android are a bridge between the Adapter View
and the underlying data for that view.
-Fragment
-Tab Title
81
private void setupViewPager(ViewPager viewPager) {
TabViewPagerAdapter adapter = new TabViewPagerAdapter(
getSupportFragmentManager());
adapter.addFrag(new MyFragmentA(), "Tab A");
adapter.addFrag(new MyFragmentB(), "Tab B");
adapter.addFrag(new MyFragmentC(), "Tab C");
viewPager.setAdapter(adapter);
}
Setup ViewPager using the
Custome
FragmentPagerAdapter
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
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 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
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
▹Test your app, You
should able to change
the fragment by
selecting the Tab and
also dragging the
fragment
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 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
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 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.
91
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
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
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.
95
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.
97
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
▹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
100
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.
102
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 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
105
Style
▹https://www.google.com/design/spec/patterns/navigation-
drawer.html#navigation-drawer-specs
106 Example Code
▹http://developer.android.com/training/implementing-navigation/nav-
drawer.html
▹https://www.youtube.com/watch?v=K8hSIP2ha-
g&list=PLonJJ3BVjZW4lMlpHgL7UNQSGMERcDzHo&index=34
▹https://www.youtube.com/watch?v=2TsJLNTgkn4&list=PLonJJ3BVjZ
W4lMlpHgL7UNQSGMERcDzHo&index=35
▹https://www.youtube.com/watch?v=6f6sbtgd6v0&list=PLonJJ3BVjZW
4lMlpHgL7UNQSGMERcDzHo&index=36
Ya! Finish!

More Related Content

Similar to Tk2323 lecture 6 fragment (new)

深入淺出談Fragment
深入淺出談Fragment深入淺出談Fragment
深入淺出談Fragment
毅 方
 
Fragment
Fragment Fragment
Fragments In Android
Fragments In AndroidFragments In Android
Fragments In Android
DivyaKS12
 
Android development session 4 - Fragments
Android development   session 4 - FragmentsAndroid development   session 4 - Fragments
Android development session 4 - Fragments
Farabi Technology Middle East
 
What the fragments
What the fragmentsWhat the fragments
What the fragments
Gowtham Kumar
 
Android App Development - 06 Fragments
Android App Development - 06 FragmentsAndroid App Development - 06 Fragments
Android App Development - 06 Fragments
Diego Grancini
 
Fragments anyone
Fragments anyone Fragments anyone
Fragments anyone
Yossi Elkrief
 
Introduction to Android Fragments
Introduction to Android FragmentsIntroduction to Android Fragments
Introduction to Android Fragments
Sergi Martínez
 
STYLISH FLOOR
STYLISH FLOORSTYLISH FLOOR
STYLISH FLOOR
ABU HASAN
 
Android apps development
Android apps developmentAndroid apps development
Android apps development
Monir Zzaman
 
04 activities - Android
04   activities - Android04   activities - Android
04 activities - Android
Wingston
 
Short Intro to Android Fragments
Short Intro to Android FragmentsShort Intro to Android Fragments
Short Intro to Android Fragments
Jussi Pohjolainen
 
Android 3
Android 3Android 3
Android 3
Robert Cooper
 
Lesson 4
Lesson 4Lesson 4
Lesson 4
CITSimon
 
Android best practices
Android best practicesAndroid best practices
Android best practices
Jose Manuel Ortega Candel
 
Architecting Single Activity Applications (With or Without Fragments)
Architecting Single Activity Applications (With or Without Fragments)Architecting Single Activity Applications (With or Without Fragments)
Architecting Single Activity Applications (With or Without Fragments)
Gabor Varadi
 
Java Svet - Communication Between Android App Components
Java Svet - Communication Between Android App ComponentsJava Svet - Communication Between Android App Components
Java Svet - Communication Between Android App Components
Aleksandar Ilić
 
Java Svet - Communication Between Android App Components
Java Svet - Communication Between Android App ComponentsJava Svet - Communication Between Android App Components
Java Svet - Communication Between Android App Components
PSTechSerbia
 
Fragmentation in android
Fragmentation in android Fragmentation in android
Fragmentation in android
Esraa El Ghoul
 
Android
AndroidAndroid
Android
Pranav Ashok
 

Similar to Tk2323 lecture 6 fragment (new) (20)

深入淺出談Fragment
深入淺出談Fragment深入淺出談Fragment
深入淺出談Fragment
 
Fragment
Fragment Fragment
Fragment
 
Fragments In Android
Fragments In AndroidFragments In Android
Fragments In Android
 
Android development session 4 - Fragments
Android development   session 4 - FragmentsAndroid development   session 4 - Fragments
Android development session 4 - Fragments
 
What the fragments
What the fragmentsWhat the fragments
What the fragments
 
Android App Development - 06 Fragments
Android App Development - 06 FragmentsAndroid App Development - 06 Fragments
Android App Development - 06 Fragments
 
Fragments anyone
Fragments anyone Fragments anyone
Fragments anyone
 
Introduction to Android Fragments
Introduction to Android FragmentsIntroduction to Android Fragments
Introduction to Android Fragments
 
STYLISH FLOOR
STYLISH FLOORSTYLISH FLOOR
STYLISH FLOOR
 
Android apps development
Android apps developmentAndroid apps development
Android apps development
 
04 activities - Android
04   activities - Android04   activities - Android
04 activities - Android
 
Short Intro to Android Fragments
Short Intro to Android FragmentsShort Intro to Android Fragments
Short Intro to Android Fragments
 
Android 3
Android 3Android 3
Android 3
 
Lesson 4
Lesson 4Lesson 4
Lesson 4
 
Android best practices
Android best practicesAndroid best practices
Android best practices
 
Architecting Single Activity Applications (With or Without Fragments)
Architecting Single Activity Applications (With or Without Fragments)Architecting Single Activity Applications (With or Without Fragments)
Architecting Single Activity Applications (With or Without Fragments)
 
Java Svet - Communication Between Android App Components
Java Svet - Communication Between Android App ComponentsJava Svet - Communication Between Android App Components
Java Svet - Communication Between Android App Components
 
Java Svet - Communication Between Android App Components
Java Svet - Communication Between Android App ComponentsJava Svet - Communication Between Android App Components
Java Svet - Communication Between Android App Components
 
Fragmentation in android
Fragmentation in android Fragmentation in android
Fragmentation in android
 
Android
AndroidAndroid
Android
 

More from MengChun Lam

Tk2323 lecture 10 sensor
Tk2323 lecture 10   sensorTk2323 lecture 10   sensor
Tk2323 lecture 10 sensor
MengChun Lam
 
Tk2323 lecture 9 api json
Tk2323 lecture 9   api jsonTk2323 lecture 9   api json
Tk2323 lecture 9 api json
MengChun Lam
 
Tk2323 lecture 8 firebase
Tk2323 lecture 8   firebaseTk2323 lecture 8   firebase
Tk2323 lecture 8 firebase
MengChun Lam
 
Tk2323 lecture 4 ui ux
Tk2323 lecture 4   ui uxTk2323 lecture 4   ui ux
Tk2323 lecture 4 ui ux
MengChun Lam
 
Tk2323 lecture 7 data storage
Tk2323 lecture 7   data storageTk2323 lecture 7   data storage
Tk2323 lecture 7 data storage
MengChun Lam
 
Tk2323 lecture 5 material design &amp; recycler view
Tk2323 lecture 5   material design &amp; recycler viewTk2323 lecture 5   material design &amp; recycler view
Tk2323 lecture 5 material design &amp; recycler view
MengChun Lam
 
Tk2323 lecture 7 sql
Tk2323 lecture 7   sql Tk2323 lecture 7   sql
Tk2323 lecture 7 sql
MengChun Lam
 
Tk2323 lecture 2 ui
Tk2323 lecture 2   uiTk2323 lecture 2   ui
Tk2323 lecture 2 ui
MengChun Lam
 
Tk2323 lecture 1 introduction to mobile application
Tk2323 lecture 1   introduction to mobile applicationTk2323 lecture 1   introduction to mobile application
Tk2323 lecture 1 introduction to mobile application
MengChun Lam
 

More from MengChun Lam (9)

Tk2323 lecture 10 sensor
Tk2323 lecture 10   sensorTk2323 lecture 10   sensor
Tk2323 lecture 10 sensor
 
Tk2323 lecture 9 api json
Tk2323 lecture 9   api jsonTk2323 lecture 9   api json
Tk2323 lecture 9 api json
 
Tk2323 lecture 8 firebase
Tk2323 lecture 8   firebaseTk2323 lecture 8   firebase
Tk2323 lecture 8 firebase
 
Tk2323 lecture 4 ui ux
Tk2323 lecture 4   ui uxTk2323 lecture 4   ui ux
Tk2323 lecture 4 ui ux
 
Tk2323 lecture 7 data storage
Tk2323 lecture 7   data storageTk2323 lecture 7   data storage
Tk2323 lecture 7 data storage
 
Tk2323 lecture 5 material design &amp; recycler view
Tk2323 lecture 5   material design &amp; recycler viewTk2323 lecture 5   material design &amp; recycler view
Tk2323 lecture 5 material design &amp; recycler view
 
Tk2323 lecture 7 sql
Tk2323 lecture 7   sql Tk2323 lecture 7   sql
Tk2323 lecture 7 sql
 
Tk2323 lecture 2 ui
Tk2323 lecture 2   uiTk2323 lecture 2   ui
Tk2323 lecture 2 ui
 
Tk2323 lecture 1 introduction to mobile application
Tk2323 lecture 1   introduction to mobile applicationTk2323 lecture 1   introduction to mobile application
Tk2323 lecture 1 introduction to mobile application
 

Tk2323 lecture 6 fragment (new)

  • 1. Fragment TK2323 Mobile Programming Sem 1 2017/2018 Lam Meng Chun lammc@ukm.edu.my (H-04-10)
  • 2. 2 Outline Navigation Drawer (Optional) 2 Fragment ▹ Fragment Lifecycle ▹ Fragment Creation ▹ Static and dynamic way Tab Layout ▹ Tab ViewPager ▹ FragmentPagerAdapter
  • 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().
  • 9. 9 Fragment Life Cycle ▹Phase II: When the fragment becomes visible, it goes through these states: ▸onStart() ▸onResume()
  • 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).
  • 11. 11 Fragment Life Cycle ▹Phase III: When the fragment goes into the background mode, it goes through these states: ▸onPaused() ▸onStop()
  • 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.
  • 17. 17 Fragment’s Life Cycle Complete Fragment’s LifeCycle https://github.com/xxv/android-lifecycle
  • 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)
  • 22. 22 Create a class that extend Fragment
  • 23. 23 Create a class that extend Fragment…
  • 24. 24 Create a class that extend Fragment…
  • 25. 25 Create a class that extend Fragment: Override the onCreateView method
  • 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
  • 31. 31 Add Fragment in activity_main layout file <fragment android:layout_width="300dp" android:name="com.tk2323.ftsm.fragment_test.MyFragmentA" android:id="@+id/fragment3" app:layout_constraintRight_toRightOf="parent" app:layout_constraintLeft_toLeftOf="parent" android:layout_height="150dp" android:layout_marginTop="16dp" app:layout_constraintTop_toBottomOf="@+id/editText2" />
  • 33. Add a Fragment to an Activity at Runtime
  • 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
  • 44. 44 Add Frag A btnFragA.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { fragmentTransaction = fragmentManager.______; fragmentTransaction.______(R.id.fragmentContainer,fragmentA); fragmentTransaction._______; } });
  • 45. 45 Replace with Fragment B btnFragA.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { fragmentTransaction = fragmentManager._______; fragmentTransaction.______(R.id.fragmentContainer,______); fragmentTransaction._______; } });
  • 46. 46 Remove Fragment B btnFragA.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { fragmentTransaction = fragmentManager.beginTransaction(); fragmentTransaction.______(______); fragmentTransaction._______; } });
  • 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.
  • 50. 50 Communicating with the Activity ▹For example: ▸MyFragmentA fragment = (MyFragmentA) getFragmentManager().findFragmentById(R.id.example_f ragment);
  • 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
  • 56. 56
  • 58. 58 Coordinate Layout ▹The Design library introduces CoordinatorLayout, a layout which provides an additional level of control over touch events between child views ▹Example of this is when you add a ▸FloatingActionButton ▸Snackbar.make() ▸Collapsed Toolbar
  • 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>
  • 69. Step 3: Prepare the XML Layout and Fragment Class
  • 70. 70 Create the Fragment XML Layout file
  • 71. 71 Create a class that extend Fragment
  • 72. 72 Add Fragment in activity_main layout file import android.support.v4.app.Fragment;
  • 73. 73 Step 4: Prepare the Main UI Layout Class
  • 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
  • 78. 78 Toolbar toolbar; TabLayout tabLayout; ViewPager viewPager; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); toolbar = (Toolbar) findViewById(R.id.main_toolbar); tabLayout = (TabLayout) findViewById(R.id.main_tabs); viewPager = (ViewPager) findViewById(R.id.main_viewpager); }
  • 79. Step 8: Setup all the view
  • 80. 80 Data Source Adapter (FragmentPa gerAdapter) Adapter View ViewPager Bridge • Adapters in Android are a bridge between the Adapter View and the underlying data for that view. -Fragment -Tab Title
  • 81. 81 private void setupViewPager(ViewPager viewPager) { TabViewPagerAdapter adapter = new TabViewPagerAdapter( getSupportFragmentManager()); adapter.addFrag(new MyFragmentA(), "Tab A"); adapter.addFrag(new MyFragmentB(), "Tab B"); adapter.addFrag(new MyFragmentC(), "Tab C"); viewPager.setAdapter(adapter); } Setup ViewPager using the Custome FragmentPagerAdapter
  • 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.
  • 91. 91
  • 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.
  • 95. 95
  • 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.
  • 97. 97
  • 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
  • 100. 100
  • 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.
  • 102. 102
  • 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

Editor's Notes

  1. Explain it
  2. Explain it