SlideShare uma empresa Scribd logo
1 de 70
Baixar para ler offline
Fragments
Why? How? What for?
Who Needs Fragments?
Who Needs Fragments?
You do!
Why?
• Smaller View Controllers
• Smaller View Controllers
• Reusable UI & Logic Components
• Smaller View Controllers
• Reusable UI & Logic Components
• Address device fragmentation
• Smaller View Controllers
• Reusable UI & Logic Components
• Address device fragmentation
• Decomposition of application code
How do they work?
Image Credit: Steve Pomeroy | github.com/xxv/android-lifecycle
Image Credit: Lars Vogel | vogella.com
onViewCreated() onViewStateRestored()
Static vs Dynamic
Static
<fragment xmlns:android="http://schemas.android.com/apk/res/android"

xmlns:tools="http://schemas.android.com/tools"

android:id="@+id/puppy_list"

android:name="com.kenodoggy.masterdetailflow.PuppyListFragment"

android:layout_width="match_parent"

android:layout_height="match_parent"

android:layout_marginLeft="16dp"

android:layout_marginRight="16dp"

tools:context=".PuppyListActivity"

tools:layout="@android:layout/list_content"/>
Instantiation
Rules you must know
public MyFragment() {

// Required empty public constructor

}
Default Constructor
public static MyFragment newInstance(int position) {

MyFragment fragment = new MyFragment();

Bundle args = new Bundle();

args.putInt(ARG_POSITION, position);

fragment.setArguments(args);

return fragment;

}
New Instances
public static MyFragment newInstance(int position) {

MyFragment fragment = new MyFragment();

Bundle args = new Bundle();

args.putInt(KEY_POSITION, position);

fragment.setArguments(args);

return fragment;

}
New Instances
Adding a Fragment
MyFragment fragment = MyFragment.newInstance(args);



getFragmentManager().beginTransaction()

.add(R.id.fragment_container, fragment)

.commit();
Adding a Fragment
MyFragment fragment = MyFragment.newInstance(args);



getFragmentManager().beginTransaction()

.add(R.id.fragment_container, fragment)

.commit();
Replacing a Fragment
MyFragment fragment = MyFragment.newInstance(args);



getFragmentManager().beginTransaction()

.replace(R.id.fragment_container, fragment)

.commit();
Destruction
Image Credit: Lars Vogel | vogella.com
onSaveInstanceState()
setRetainInstance(true)
@Override

public void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);



// Retain this fragment across configuration changes.

setRetainInstance(true);

}
Examples
Dual / Single Pane Design
aka Master / Detail
Specifying Layouts Based on
Screen Properties
Navigation Layout for Phone
<fragment xmlns:android="http://schemas.android.com/apk/res/android"

xmlns:tools="http://schemas.android.com/tools"

android:id="@+id/puppy_list"

android:name="com.kenodoggy.masterdetailflow.PuppyListFragment"

android:layout_width="match_parent"

android:layout_height="match_parent"

android:layout_marginLeft="16dp"

android:layout_marginRight="16dp"

tools:context=".PuppyListActivity"

tools:layout="@android:layout/list_content"/>
Detail Layout for Phone
<android.support.design.widget.CoordinatorLayout>

<android.support.design.widget.AppBarLayout>

<android.support.design.widget.CollapsingToolbarLayout>

<android.support.v7.widget.Toolbar />

</android.support.design.widget.CollapsingToolbarLayout>

</android.support.design.widget.AppBarLayout>


<android.support.v4.widget.NestedScrollView

android:id="@+id/puppy_detail_container"

android:layout_width="match_parent"

android:layout_height="match_parent"

app:layout_behavior=“@string/appbar_scrolling_view_behavior"/>


</android.support.design.widget.CoordinatorLayout>

List/Detail Layout for Tablet
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"

xmlns:tools="http://schemas.android.com/tools"

android:orientation="horizontal">



<fragment

android:id="@+id/puppy_list"

android:name="com.kenodoggy.masterdetailflow.PuppyListFragment"

android:layout_width="0dp"

android:layout_height="match_parent"

android:layout_weight="1"

tools:layout="@android:layout/list_content"/>



<FrameLayout

android:id="@+id/puppy_detail_container"

android:layout_width="0dp"

android:layout_height="match_parent"

android:layout_weight="3"/>



</LinearLayout>
Determining Which Layout to Display
Dual or Single Pane?
if (findViewById(R.id.puppy_detail_container) != null) {

// The detail container view will be present only in the

// large-screen layouts (res/values-large and

// res/values-sw600dp). If this view is present, then the

// activity should be in two-pane mode.

mTwoPane = true;



... code specific to two pane layout

}
Tabbed ViewPager
The Parent Activity Layout
<android.support.design.widget.CoordinatorLayout>

<android.support.design.widget.AppBarLayout>

<android.support.v7.widget.Toolbar />



<android.support.design.widget.TabLayout android:id="@+id/tabs"

android:layout_width=“wrap_content" android:layout_height="wrap_content"

app:tabMode="scrollable"/>



</android.support.design.widget.AppBarLayout>



<android.support.v4.view.ViewPager android:id="@+id/container"

android:layout_width="match_parent" android:layout_height="match_parent"

app:layout_behavior="@string/appbar_scrolling_view_behavior" />



</android.support.design.widget.CoordinatorLayout>
The Parent Activity Layout
<android.support.design.widget.CoordinatorLayout>

<android.support.design.widget.AppBarLayout>

<android.support.v7.widget.Toolbar />



<android.support.design.widget.TabLayout android:id="@+id/tabs"

android:layout_width=“wrap_content" android:layout_height="wrap_content"

app:tabMode="scrollable"/>



</android.support.design.widget.AppBarLayout>



<android.support.v4.view.ViewPager android:id="@+id/container"

android:layout_width="match_parent" android:layout_height="match_parent"

app:layout_behavior="@string/appbar_scrolling_view_behavior" />



</android.support.design.widget.CoordinatorLayout>
Setting up our ViewPager


ViewPagerAdapter adapter =
new ViewPagerAdapter(getSupportFragmentManager());



/* add the Fragments to the ViewPagerAdapter */

for(String title : mPuppyTitles) {

adapter.addFrag(PuppyFragment.newInstance(index++), title);

}



mViewPager.setAdapter(adapter);
Creating our PuppyFragment
@Override

public void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

if (getArguments() != null) {

mPageNumber = getArguments().getInt(ARG_POSITION);

}

}
Loading the UI
@Override

public View onCreateView(LayoutInflater inflater, ViewGroup container,

Bundle savedInstanceState)
{

View view = inflater.inflate(R.layout.fragment_puppy, container, false);



int imageId = getResources().getIdentifier(mPuppyImages[mPageNumber],

"drawable", getActivity().getPackageName());


ImageView image = (ImageView) view.findViewById(R.id.puppy_picture);

image.setImageResource(imageId);



return view;

}
Loading the UI
@Override

public View onCreateView(LayoutInflater inflater, ViewGroup container,

Bundle savedInstanceState)
{

View view = inflater.inflate(R.layout.fragment_puppy, container, false);



int imageId = getResources().getIdentifier(mPuppyImages[mPageNumber],

"drawable", getActivity().getPackageName());


ImageView image = (ImageView) view.findViewById(R.id.puppy_picture);

image.setImageResource(imageId);



return view;

}
Navigation Drawer
Fragment fragment = DetailFragment.newInstance(puppy, position);



FragmentManager fragmentManager = getFragmentManager();

FragmentTransaction transaction = fragmentManager.beginTransaction();

// do replace and commit operation

transaction.replace(R.id.detail_container, fragment).commit();
Fragment fragment = DetailFragment.newInstance(puppy, position);



FragmentManager fragmentManager = getFragmentManager();

FragmentTransaction transaction = fragmentManager.beginTransaction();

// do replace, add to backstack and commit operation

transaction.replace(R.id.detail_container, fragment)
.addToBackStack(“details”) // optional name for this back stack state, or null
.commit();
Going Back
• Fragment: popBackStack()
• Activity: onBackPressed()
DialogFragment
Constructing a DialogFragment
Two ways:
Constructing a DialogFragment
Two ways:
@Override onCreateView()
Constructing a DialogFragment
Two ways:
@Override onCreateDialog()
@Override onCreateView()
public class SampleDialogFragment extends DialogFragment
implements DialogInterface.OnClickListener {

@Override

public Dialog onCreateDialog(Bundle savedInstanceState) {

View view = getActivity()
.getLayoutInflater()
.inflate(R.layout.fragment_sample_dialog, null);



AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());



return(builder

.setView(view)

.setTitle(title)

.setPositiveButton(R.string.close, null)

.create());

}

}
public class SampleDialogFragment extends DialogFragment
implements DialogInterface.OnClickListener {

@Override

public Dialog onCreateDialog(Bundle savedInstanceState) {

View view = getActivity()
.getLayoutInflater()
.inflate(R.layout.fragment_sample_dialog, null);



AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());



return(builder

.setView(view)

.setTitle(title)

.setPositiveButton(R.string.close, null)

.create());

}

}
public class SampleDialogFragment extends DialogFragment
implements DialogInterface.OnClickListener {

@Override

public Dialog onCreateDialog(Bundle savedInstanceState) {

View view = getActivity()
.getLayoutInflater()
.inflate(R.layout.fragment_sample_dialog, null);



AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());



return(builder

.setView(view)

.setCustomTitle(title)

.setPositiveButton(R.string.close, null)

.create());

}

}
Showing your DialogFragment
SampleDialogFragment frag = SampleDialogFragment.newInstance(args);
frag.show(getFragmentManager(), SampleDialogFragment.TAG);


return(builder

.setTitle(title)
.setMessage(“Dialog Message”)

.setPositiveButton(R.string.close, null)

.create());

Dismissing a DialogFragment
Communicating with the
Parent Activity
Define an Interface
public interface OnDialogDismissed {

void onDialogDismissed(String whichSalutation);

}
@Override

public void onAttach(Activity activity) {

super.onAttach(activity);

try {

mDialogDismissedCallback = (OnDialogDismissed)activity;

} catch (ClassCastException cce) {

Log.e("Error", getClass().getSimpleName()
+ ", calling Activity must implement OnDialogDismissed");

}

}
public class MainActivity extends AppCompatActivity implements
SampleDialogFragment.OnDialogDismissed {

// ... other methods and implementation not shown

@Override

public void onDialogDismissed(String whichSalutation) {

if (whichSalutation.equals(SampleDialogFragment.GOODBYE)) {

Toast.makeText(this, "Thank you!", Toast.LENGTH_SHORT).show();

}

}

}
@Override

public void onClick(DialogInterface dialog, int which) {

// display a toast when the dialog is dismissed for GOODBYE only

if (mSalutation.equals(GOODBYE)) {

mDialogDismissedCallback.onDialogDismissed(GOODBYE);

}

}
Thank you
Source Code github.com/kenodoggy/
Slides slideshare.net/kenodoggy/fragments-why-how-what-for
Twitter @kenodoggy
g+ +BrendaCook_kenodoggy

Mais conteúdo relacionado

Mais procurados

Mais procurados (20)

Android Components
Android ComponentsAndroid Components
Android Components
 
Multi Window in Android N
Multi Window in Android NMulti Window in Android N
Multi Window in Android N
 
Dagger in multi module sdk
Dagger in multi module sdkDagger in multi module sdk
Dagger in multi module sdk
 
Android N multi window
Android N multi windowAndroid N multi window
Android N multi window
 
04 user interfaces
04 user interfaces04 user interfaces
04 user interfaces
 
Android UI Fundamentals part 1
Android UI Fundamentals part 1Android UI Fundamentals part 1
Android UI Fundamentals part 1
 
Ppt 2 android_basics
Ppt 2 android_basicsPpt 2 android_basics
Ppt 2 android_basics
 
Fragmentation in android
Fragmentation in android Fragmentation in android
Fragmentation in android
 
Android Basic Components
Android Basic ComponentsAndroid Basic Components
Android Basic Components
 
Android apps development
Android apps developmentAndroid apps development
Android apps development
 
I/O Rewind 215: What's new in Android
I/O Rewind 215: What's new in AndroidI/O Rewind 215: What's new in Android
I/O Rewind 215: What's new in Android
 
Android best practices
Android best practicesAndroid best practices
Android best practices
 
Android development - Activities, Views & Intents
Android development - Activities, Views & IntentsAndroid development - Activities, Views & Intents
Android development - Activities, Views & Intents
 
Atomic Designは「マルチ」で真価を発揮する
Atomic Designは「マルチ」で真価を発揮するAtomic Designは「マルチ」で真価を発揮する
Atomic Designは「マルチ」で真価を発揮する
 
Android in practice
Android in practiceAndroid in practice
Android in practice
 
Android appwidget
Android appwidgetAndroid appwidget
Android appwidget
 
Hierarchy viewer
Hierarchy viewerHierarchy viewer
Hierarchy viewer
 
Day 4: Activity lifecycle
Day 4: Activity lifecycleDay 4: Activity lifecycle
Day 4: Activity lifecycle
 
Android Widget
Android WidgetAndroid Widget
Android Widget
 
Fragments
FragmentsFragments
Fragments
 

Semelhante a Fragments: Why, How, What For?

Data binding 入門淺談
Data binding 入門淺談Data binding 入門淺談
Data binding 入門淺談awonwon
 
How to use data binding in android
How to use data binding in androidHow to use data binding in android
How to use data binding in androidInnovationM
 
Beginning Native Android Apps
Beginning Native Android AppsBeginning Native Android Apps
Beginning Native Android AppsGil Irizarry
 
06. Android Basic Widget and Container
06. Android Basic Widget and Container06. Android Basic Widget and Container
06. Android Basic Widget and ContainerOum Saokosal
 
Angular server side rendering - Strategies & Technics
Angular server side rendering - Strategies & Technics Angular server side rendering - Strategies & Technics
Angular server side rendering - Strategies & Technics Eliran Eliassy
 
Invading the home screen
Invading the home screenInvading the home screen
Invading the home screenMatteo Bonifazi
 
Material Design (The Technical Essentials) by Mohammad Aljobairi @AMMxDROID
Material Design (The Technical Essentials) by Mohammad Aljobairi @AMMxDROIDMaterial Design (The Technical Essentials) by Mohammad Aljobairi @AMMxDROID
Material Design (The Technical Essentials) by Mohammad Aljobairi @AMMxDROIDJordan Open Source Association
 
Support Design Library
Support Design LibrarySupport Design Library
Support Design LibraryTaeho Kim
 
[2019] 스몰 스텝: Android 렛츠기릿!
[2019] 스몰 스텝: Android 렛츠기릿![2019] 스몰 스텝: Android 렛츠기릿!
[2019] 스몰 스텝: Android 렛츠기릿!NHN FORWARD
 
android layouts
android layoutsandroid layouts
android layoutsDeepa Rani
 
Android Apps Development Basic
Android Apps Development BasicAndroid Apps Development Basic
Android Apps Development BasicMonir Zzaman
 
Android Material Design APIs/Tips
Android Material Design APIs/TipsAndroid Material Design APIs/Tips
Android Material Design APIs/TipsKen Yee
 
Design Patterns for Tablets and Smartphones
Design Patterns for Tablets and SmartphonesDesign Patterns for Tablets and Smartphones
Design Patterns for Tablets and SmartphonesMichael Galpin
 
Android Workshop
Android WorkshopAndroid Workshop
Android WorkshopJunda Ong
 
Infinum Android Talks #14 - Data binding to the rescue... or not (?) by Krist...
Infinum Android Talks #14 - Data binding to the rescue... or not (?) by Krist...Infinum Android Talks #14 - Data binding to the rescue... or not (?) by Krist...
Infinum Android Talks #14 - Data binding to the rescue... or not (?) by Krist...Infinum
 
Lecture #1 Creating your first android project
Lecture #1  Creating your first android projectLecture #1  Creating your first android project
Lecture #1 Creating your first android projectVitali Pekelis
 

Semelhante a Fragments: Why, How, What For? (20)

Data binding 入門淺談
Data binding 入門淺談Data binding 入門淺談
Data binding 入門淺談
 
How to use data binding in android
How to use data binding in androidHow to use data binding in android
How to use data binding in android
 
Beginning Native Android Apps
Beginning Native Android AppsBeginning Native Android Apps
Beginning Native Android Apps
 
06. Android Basic Widget and Container
06. Android Basic Widget and Container06. Android Basic Widget and Container
06. Android Basic Widget and Container
 
Angular server side rendering - Strategies & Technics
Angular server side rendering - Strategies & Technics Angular server side rendering - Strategies & Technics
Angular server side rendering - Strategies & Technics
 
Invading the home screen
Invading the home screenInvading the home screen
Invading the home screen
 
Material Design (The Technical Essentials) by Mohammad Aljobairi @AMMxDROID
Material Design (The Technical Essentials) by Mohammad Aljobairi @AMMxDROIDMaterial Design (The Technical Essentials) by Mohammad Aljobairi @AMMxDROID
Material Design (The Technical Essentials) by Mohammad Aljobairi @AMMxDROID
 
Android Materials Design
Android Materials Design Android Materials Design
Android Materials Design
 
Support Design Library
Support Design LibrarySupport Design Library
Support Design Library
 
Chapter 5 - Layouts
Chapter 5 - LayoutsChapter 5 - Layouts
Chapter 5 - Layouts
 
[2019] 스몰 스텝: Android 렛츠기릿!
[2019] 스몰 스텝: Android 렛츠기릿![2019] 스몰 스텝: Android 렛츠기릿!
[2019] 스몰 스텝: Android 렛츠기릿!
 
android layouts
android layoutsandroid layouts
android layouts
 
06 UI Layout
06 UI Layout06 UI Layout
06 UI Layout
 
Android Apps Development Basic
Android Apps Development BasicAndroid Apps Development Basic
Android Apps Development Basic
 
Android Material Design APIs/Tips
Android Material Design APIs/TipsAndroid Material Design APIs/Tips
Android Material Design APIs/Tips
 
Layouts in android
Layouts in androidLayouts in android
Layouts in android
 
Design Patterns for Tablets and Smartphones
Design Patterns for Tablets and SmartphonesDesign Patterns for Tablets and Smartphones
Design Patterns for Tablets and Smartphones
 
Android Workshop
Android WorkshopAndroid Workshop
Android Workshop
 
Infinum Android Talks #14 - Data binding to the rescue... or not (?) by Krist...
Infinum Android Talks #14 - Data binding to the rescue... or not (?) by Krist...Infinum Android Talks #14 - Data binding to the rescue... or not (?) by Krist...
Infinum Android Talks #14 - Data binding to the rescue... or not (?) by Krist...
 
Lecture #1 Creating your first android project
Lecture #1  Creating your first android projectLecture #1  Creating your first android project
Lecture #1 Creating your first android project
 

Último

SensoDat: Simulation-based Sensor Dataset of Self-driving Cars
SensoDat: Simulation-based Sensor Dataset of Self-driving CarsSensoDat: Simulation-based Sensor Dataset of Self-driving Cars
SensoDat: Simulation-based Sensor Dataset of Self-driving CarsChristian Birchler
 
Best Angular 17 Classroom & Online training - Naresh IT
Best Angular 17 Classroom & Online training - Naresh ITBest Angular 17 Classroom & Online training - Naresh IT
Best Angular 17 Classroom & Online training - Naresh ITmanoharjgpsolutions
 
Real-time Tracking and Monitoring with Cargo Cloud Solutions.pptx
Real-time Tracking and Monitoring with Cargo Cloud Solutions.pptxReal-time Tracking and Monitoring with Cargo Cloud Solutions.pptx
Real-time Tracking and Monitoring with Cargo Cloud Solutions.pptxRTS corp
 
SAM Training Session - How to use EXCEL ?
SAM Training Session - How to use EXCEL ?SAM Training Session - How to use EXCEL ?
SAM Training Session - How to use EXCEL ?Alexandre Beguel
 
Strategies for using alternative queries to mitigate zero results
Strategies for using alternative queries to mitigate zero resultsStrategies for using alternative queries to mitigate zero results
Strategies for using alternative queries to mitigate zero resultsJean Silva
 
Patterns for automating API delivery. API conference
Patterns for automating API delivery. API conferencePatterns for automating API delivery. API conference
Patterns for automating API delivery. API conferencessuser9e7c64
 
Simplifying Microservices & Apps - The art of effortless development - Meetup...
Simplifying Microservices & Apps - The art of effortless development - Meetup...Simplifying Microservices & Apps - The art of effortless development - Meetup...
Simplifying Microservices & Apps - The art of effortless development - Meetup...Rob Geurden
 
Salesforce Implementation Services PPT By ABSYZ
Salesforce Implementation Services PPT By ABSYZSalesforce Implementation Services PPT By ABSYZ
Salesforce Implementation Services PPT By ABSYZABSYZ Inc
 
Understanding Flamingo - DeepMind's VLM Architecture
Understanding Flamingo - DeepMind's VLM ArchitectureUnderstanding Flamingo - DeepMind's VLM Architecture
Understanding Flamingo - DeepMind's VLM Architecturerahul_net
 
VictoriaMetrics Q1 Meet Up '24 - Community & News Update
VictoriaMetrics Q1 Meet Up '24 - Community & News UpdateVictoriaMetrics Q1 Meet Up '24 - Community & News Update
VictoriaMetrics Q1 Meet Up '24 - Community & News UpdateVictoriaMetrics
 
Osi security architecture in network.pptx
Osi security architecture in network.pptxOsi security architecture in network.pptx
Osi security architecture in network.pptxVinzoCenzo
 
eSoftTools IMAP Backup Software and migration tools
eSoftTools IMAP Backup Software and migration toolseSoftTools IMAP Backup Software and migration tools
eSoftTools IMAP Backup Software and migration toolsosttopstonverter
 
UI5ers live - Custom Controls wrapping 3rd-party libs.pptx
UI5ers live - Custom Controls wrapping 3rd-party libs.pptxUI5ers live - Custom Controls wrapping 3rd-party libs.pptx
UI5ers live - Custom Controls wrapping 3rd-party libs.pptxAndreas Kunz
 
OpenChain Education Work Group Monthly Meeting - 2024-04-10 - Full Recording
OpenChain Education Work Group Monthly Meeting - 2024-04-10 - Full RecordingOpenChain Education Work Group Monthly Meeting - 2024-04-10 - Full Recording
OpenChain Education Work Group Monthly Meeting - 2024-04-10 - Full RecordingShane Coughlan
 
Machine Learning Software Engineering Patterns and Their Engineering
Machine Learning Software Engineering Patterns and Their EngineeringMachine Learning Software Engineering Patterns and Their Engineering
Machine Learning Software Engineering Patterns and Their EngineeringHironori Washizaki
 
Large Language Models for Test Case Evolution and Repair
Large Language Models for Test Case Evolution and RepairLarge Language Models for Test Case Evolution and Repair
Large Language Models for Test Case Evolution and RepairLionel Briand
 
Leveraging AI for Mobile App Testing on Real Devices | Applitools + Kobiton
Leveraging AI for Mobile App Testing on Real Devices | Applitools + KobitonLeveraging AI for Mobile App Testing on Real Devices | Applitools + Kobiton
Leveraging AI for Mobile App Testing on Real Devices | Applitools + KobitonApplitools
 
Enhancing Supply Chain Visibility with Cargo Cloud Solutions.pdf
Enhancing Supply Chain Visibility with Cargo Cloud Solutions.pdfEnhancing Supply Chain Visibility with Cargo Cloud Solutions.pdf
Enhancing Supply Chain Visibility with Cargo Cloud Solutions.pdfRTS corp
 
Comparing Linux OS Image Update Models - EOSS 2024.pdf
Comparing Linux OS Image Update Models - EOSS 2024.pdfComparing Linux OS Image Update Models - EOSS 2024.pdf
Comparing Linux OS Image Update Models - EOSS 2024.pdfDrew Moseley
 
Post Quantum Cryptography – The Impact on Identity
Post Quantum Cryptography – The Impact on IdentityPost Quantum Cryptography – The Impact on Identity
Post Quantum Cryptography – The Impact on Identityteam-WIBU
 

Último (20)

SensoDat: Simulation-based Sensor Dataset of Self-driving Cars
SensoDat: Simulation-based Sensor Dataset of Self-driving CarsSensoDat: Simulation-based Sensor Dataset of Self-driving Cars
SensoDat: Simulation-based Sensor Dataset of Self-driving Cars
 
Best Angular 17 Classroom & Online training - Naresh IT
Best Angular 17 Classroom & Online training - Naresh ITBest Angular 17 Classroom & Online training - Naresh IT
Best Angular 17 Classroom & Online training - Naresh IT
 
Real-time Tracking and Monitoring with Cargo Cloud Solutions.pptx
Real-time Tracking and Monitoring with Cargo Cloud Solutions.pptxReal-time Tracking and Monitoring with Cargo Cloud Solutions.pptx
Real-time Tracking and Monitoring with Cargo Cloud Solutions.pptx
 
SAM Training Session - How to use EXCEL ?
SAM Training Session - How to use EXCEL ?SAM Training Session - How to use EXCEL ?
SAM Training Session - How to use EXCEL ?
 
Strategies for using alternative queries to mitigate zero results
Strategies for using alternative queries to mitigate zero resultsStrategies for using alternative queries to mitigate zero results
Strategies for using alternative queries to mitigate zero results
 
Patterns for automating API delivery. API conference
Patterns for automating API delivery. API conferencePatterns for automating API delivery. API conference
Patterns for automating API delivery. API conference
 
Simplifying Microservices & Apps - The art of effortless development - Meetup...
Simplifying Microservices & Apps - The art of effortless development - Meetup...Simplifying Microservices & Apps - The art of effortless development - Meetup...
Simplifying Microservices & Apps - The art of effortless development - Meetup...
 
Salesforce Implementation Services PPT By ABSYZ
Salesforce Implementation Services PPT By ABSYZSalesforce Implementation Services PPT By ABSYZ
Salesforce Implementation Services PPT By ABSYZ
 
Understanding Flamingo - DeepMind's VLM Architecture
Understanding Flamingo - DeepMind's VLM ArchitectureUnderstanding Flamingo - DeepMind's VLM Architecture
Understanding Flamingo - DeepMind's VLM Architecture
 
VictoriaMetrics Q1 Meet Up '24 - Community & News Update
VictoriaMetrics Q1 Meet Up '24 - Community & News UpdateVictoriaMetrics Q1 Meet Up '24 - Community & News Update
VictoriaMetrics Q1 Meet Up '24 - Community & News Update
 
Osi security architecture in network.pptx
Osi security architecture in network.pptxOsi security architecture in network.pptx
Osi security architecture in network.pptx
 
eSoftTools IMAP Backup Software and migration tools
eSoftTools IMAP Backup Software and migration toolseSoftTools IMAP Backup Software and migration tools
eSoftTools IMAP Backup Software and migration tools
 
UI5ers live - Custom Controls wrapping 3rd-party libs.pptx
UI5ers live - Custom Controls wrapping 3rd-party libs.pptxUI5ers live - Custom Controls wrapping 3rd-party libs.pptx
UI5ers live - Custom Controls wrapping 3rd-party libs.pptx
 
OpenChain Education Work Group Monthly Meeting - 2024-04-10 - Full Recording
OpenChain Education Work Group Monthly Meeting - 2024-04-10 - Full RecordingOpenChain Education Work Group Monthly Meeting - 2024-04-10 - Full Recording
OpenChain Education Work Group Monthly Meeting - 2024-04-10 - Full Recording
 
Machine Learning Software Engineering Patterns and Their Engineering
Machine Learning Software Engineering Patterns and Their EngineeringMachine Learning Software Engineering Patterns and Their Engineering
Machine Learning Software Engineering Patterns and Their Engineering
 
Large Language Models for Test Case Evolution and Repair
Large Language Models for Test Case Evolution and RepairLarge Language Models for Test Case Evolution and Repair
Large Language Models for Test Case Evolution and Repair
 
Leveraging AI for Mobile App Testing on Real Devices | Applitools + Kobiton
Leveraging AI for Mobile App Testing on Real Devices | Applitools + KobitonLeveraging AI for Mobile App Testing on Real Devices | Applitools + Kobiton
Leveraging AI for Mobile App Testing on Real Devices | Applitools + Kobiton
 
Enhancing Supply Chain Visibility with Cargo Cloud Solutions.pdf
Enhancing Supply Chain Visibility with Cargo Cloud Solutions.pdfEnhancing Supply Chain Visibility with Cargo Cloud Solutions.pdf
Enhancing Supply Chain Visibility with Cargo Cloud Solutions.pdf
 
Comparing Linux OS Image Update Models - EOSS 2024.pdf
Comparing Linux OS Image Update Models - EOSS 2024.pdfComparing Linux OS Image Update Models - EOSS 2024.pdf
Comparing Linux OS Image Update Models - EOSS 2024.pdf
 
Post Quantum Cryptography – The Impact on Identity
Post Quantum Cryptography – The Impact on IdentityPost Quantum Cryptography – The Impact on Identity
Post Quantum Cryptography – The Impact on Identity
 

Fragments: Why, How, What For?

  • 5. • Smaller View Controllers
  • 6. • Smaller View Controllers • Reusable UI & Logic Components
  • 7. • Smaller View Controllers • Reusable UI & Logic Components • Address device fragmentation
  • 8. • Smaller View Controllers • Reusable UI & Logic Components • Address device fragmentation • Decomposition of application code
  • 9. How do they work?
  • 10. Image Credit: Steve Pomeroy | github.com/xxv/android-lifecycle
  • 11. Image Credit: Lars Vogel | vogella.com
  • 16. public MyFragment() {
 // Required empty public constructor
 } Default Constructor
  • 17. public static MyFragment newInstance(int position) {
 MyFragment fragment = new MyFragment();
 Bundle args = new Bundle();
 args.putInt(ARG_POSITION, position);
 fragment.setArguments(args);
 return fragment;
 } New Instances
  • 18. public static MyFragment newInstance(int position) {
 MyFragment fragment = new MyFragment();
 Bundle args = new Bundle();
 args.putInt(KEY_POSITION, position);
 fragment.setArguments(args);
 return fragment;
 } New Instances
  • 19. Adding a Fragment MyFragment fragment = MyFragment.newInstance(args);
 
 getFragmentManager().beginTransaction()
 .add(R.id.fragment_container, fragment)
 .commit();
  • 20. Adding a Fragment MyFragment fragment = MyFragment.newInstance(args);
 
 getFragmentManager().beginTransaction()
 .add(R.id.fragment_container, fragment)
 .commit();
  • 21. Replacing a Fragment MyFragment fragment = MyFragment.newInstance(args);
 
 getFragmentManager().beginTransaction()
 .replace(R.id.fragment_container, fragment)
 .commit();
  • 22.
  • 24. Image Credit: Lars Vogel | vogella.com onSaveInstanceState()
  • 25. setRetainInstance(true) @Override
 public void onCreate(Bundle savedInstanceState) {
 super.onCreate(savedInstanceState);
 
 // Retain this fragment across configuration changes.
 setRetainInstance(true);
 }
  • 27. Dual / Single Pane Design aka Master / Detail
  • 28.
  • 29. Specifying Layouts Based on Screen Properties
  • 30. Navigation Layout for Phone <fragment xmlns:android="http://schemas.android.com/apk/res/android"
 xmlns:tools="http://schemas.android.com/tools"
 android:id="@+id/puppy_list"
 android:name="com.kenodoggy.masterdetailflow.PuppyListFragment"
 android:layout_width="match_parent"
 android:layout_height="match_parent"
 android:layout_marginLeft="16dp"
 android:layout_marginRight="16dp"
 tools:context=".PuppyListActivity"
 tools:layout="@android:layout/list_content"/>
  • 31. Detail Layout for Phone <android.support.design.widget.CoordinatorLayout>
 <android.support.design.widget.AppBarLayout>
 <android.support.design.widget.CollapsingToolbarLayout>
 <android.support.v7.widget.Toolbar />
 </android.support.design.widget.CollapsingToolbarLayout>
 </android.support.design.widget.AppBarLayout> 
 <android.support.v4.widget.NestedScrollView
 android:id="@+id/puppy_detail_container"
 android:layout_width="match_parent"
 android:layout_height="match_parent"
 app:layout_behavior=“@string/appbar_scrolling_view_behavior"/> 
 </android.support.design.widget.CoordinatorLayout>

  • 32.
  • 33. List/Detail Layout for Tablet <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
 xmlns:tools="http://schemas.android.com/tools"
 android:orientation="horizontal">
 
 <fragment
 android:id="@+id/puppy_list"
 android:name="com.kenodoggy.masterdetailflow.PuppyListFragment"
 android:layout_width="0dp"
 android:layout_height="match_parent"
 android:layout_weight="1"
 tools:layout="@android:layout/list_content"/>
 
 <FrameLayout
 android:id="@+id/puppy_detail_container"
 android:layout_width="0dp"
 android:layout_height="match_parent"
 android:layout_weight="3"/>
 
 </LinearLayout>
  • 35.
  • 36.
  • 37.
  • 38.
  • 39. Dual or Single Pane? if (findViewById(R.id.puppy_detail_container) != null) {
 // The detail container view will be present only in the
 // large-screen layouts (res/values-large and
 // res/values-sw600dp). If this view is present, then the
 // activity should be in two-pane mode.
 mTwoPane = true;
 
 ... code specific to two pane layout
 }
  • 41.
  • 42. The Parent Activity Layout <android.support.design.widget.CoordinatorLayout>
 <android.support.design.widget.AppBarLayout>
 <android.support.v7.widget.Toolbar />
 
 <android.support.design.widget.TabLayout android:id="@+id/tabs"
 android:layout_width=“wrap_content" android:layout_height="wrap_content"
 app:tabMode="scrollable"/>
 
 </android.support.design.widget.AppBarLayout>
 
 <android.support.v4.view.ViewPager android:id="@+id/container"
 android:layout_width="match_parent" android:layout_height="match_parent"
 app:layout_behavior="@string/appbar_scrolling_view_behavior" />
 
 </android.support.design.widget.CoordinatorLayout>
  • 43. The Parent Activity Layout <android.support.design.widget.CoordinatorLayout>
 <android.support.design.widget.AppBarLayout>
 <android.support.v7.widget.Toolbar />
 
 <android.support.design.widget.TabLayout android:id="@+id/tabs"
 android:layout_width=“wrap_content" android:layout_height="wrap_content"
 app:tabMode="scrollable"/>
 
 </android.support.design.widget.AppBarLayout>
 
 <android.support.v4.view.ViewPager android:id="@+id/container"
 android:layout_width="match_parent" android:layout_height="match_parent"
 app:layout_behavior="@string/appbar_scrolling_view_behavior" />
 
 </android.support.design.widget.CoordinatorLayout>
  • 44. Setting up our ViewPager 
 ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
 
 /* add the Fragments to the ViewPagerAdapter */
 for(String title : mPuppyTitles) {
 adapter.addFrag(PuppyFragment.newInstance(index++), title);
 }
 
 mViewPager.setAdapter(adapter);
  • 45. Creating our PuppyFragment @Override
 public void onCreate(Bundle savedInstanceState) {
 super.onCreate(savedInstanceState);
 if (getArguments() != null) {
 mPageNumber = getArguments().getInt(ARG_POSITION);
 }
 }
  • 46. Loading the UI @Override
 public View onCreateView(LayoutInflater inflater, ViewGroup container,
 Bundle savedInstanceState) {
 View view = inflater.inflate(R.layout.fragment_puppy, container, false);
 
 int imageId = getResources().getIdentifier(mPuppyImages[mPageNumber],
 "drawable", getActivity().getPackageName()); 
 ImageView image = (ImageView) view.findViewById(R.id.puppy_picture);
 image.setImageResource(imageId);
 
 return view;
 }
  • 47. Loading the UI @Override
 public View onCreateView(LayoutInflater inflater, ViewGroup container,
 Bundle savedInstanceState) {
 View view = inflater.inflate(R.layout.fragment_puppy, container, false);
 
 int imageId = getResources().getIdentifier(mPuppyImages[mPageNumber],
 "drawable", getActivity().getPackageName()); 
 ImageView image = (ImageView) view.findViewById(R.id.puppy_picture);
 image.setImageResource(imageId);
 
 return view;
 }
  • 49.
  • 50.
  • 51. Fragment fragment = DetailFragment.newInstance(puppy, position);
 
 FragmentManager fragmentManager = getFragmentManager();
 FragmentTransaction transaction = fragmentManager.beginTransaction();
 // do replace and commit operation
 transaction.replace(R.id.detail_container, fragment).commit();
  • 52. Fragment fragment = DetailFragment.newInstance(puppy, position);
 
 FragmentManager fragmentManager = getFragmentManager();
 FragmentTransaction transaction = fragmentManager.beginTransaction();
 // do replace, add to backstack and commit operation
 transaction.replace(R.id.detail_container, fragment) .addToBackStack(“details”) // optional name for this back stack state, or null .commit();
  • 53. Going Back • Fragment: popBackStack() • Activity: onBackPressed()
  • 56. Constructing a DialogFragment Two ways: @Override onCreateView()
  • 57. Constructing a DialogFragment Two ways: @Override onCreateDialog() @Override onCreateView()
  • 58. public class SampleDialogFragment extends DialogFragment implements DialogInterface.OnClickListener {
 @Override
 public Dialog onCreateDialog(Bundle savedInstanceState) {
 View view = getActivity() .getLayoutInflater() .inflate(R.layout.fragment_sample_dialog, null);
 
 AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
 
 return(builder
 .setView(view)
 .setTitle(title)
 .setPositiveButton(R.string.close, null)
 .create());
 }
 }
  • 59. public class SampleDialogFragment extends DialogFragment implements DialogInterface.OnClickListener {
 @Override
 public Dialog onCreateDialog(Bundle savedInstanceState) {
 View view = getActivity() .getLayoutInflater() .inflate(R.layout.fragment_sample_dialog, null);
 
 AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
 
 return(builder
 .setView(view)
 .setTitle(title)
 .setPositiveButton(R.string.close, null)
 .create());
 }
 }
  • 60. public class SampleDialogFragment extends DialogFragment implements DialogInterface.OnClickListener {
 @Override
 public Dialog onCreateDialog(Bundle savedInstanceState) {
 View view = getActivity() .getLayoutInflater() .inflate(R.layout.fragment_sample_dialog, null);
 
 AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
 
 return(builder
 .setView(view)
 .setCustomTitle(title)
 .setPositiveButton(R.string.close, null)
 .create());
 }
 }
  • 61. Showing your DialogFragment SampleDialogFragment frag = SampleDialogFragment.newInstance(args); frag.show(getFragmentManager(), SampleDialogFragment.TAG);
  • 63.
  • 66. Define an Interface public interface OnDialogDismissed {
 void onDialogDismissed(String whichSalutation);
 }
  • 67. @Override
 public void onAttach(Activity activity) {
 super.onAttach(activity);
 try {
 mDialogDismissedCallback = (OnDialogDismissed)activity;
 } catch (ClassCastException cce) {
 Log.e("Error", getClass().getSimpleName() + ", calling Activity must implement OnDialogDismissed");
 }
 }
  • 68. public class MainActivity extends AppCompatActivity implements SampleDialogFragment.OnDialogDismissed {
 // ... other methods and implementation not shown
 @Override
 public void onDialogDismissed(String whichSalutation) {
 if (whichSalutation.equals(SampleDialogFragment.GOODBYE)) {
 Toast.makeText(this, "Thank you!", Toast.LENGTH_SHORT).show();
 }
 }
 }
  • 69. @Override
 public void onClick(DialogInterface dialog, int which) {
 // display a toast when the dialog is dismissed for GOODBYE only
 if (mSalutation.equals(GOODBYE)) {
 mDialogDismissedCallback.onDialogDismissed(GOODBYE);
 }
 }
  • 70. Thank you Source Code github.com/kenodoggy/ Slides slideshare.net/kenodoggy/fragments-why-how-what-for Twitter @kenodoggy g+ +BrendaCook_kenodoggy