SlideShare uma empresa Scribd logo
1 de 19
Baixar para ler offline
Fragments anyone?
      Leonid Olevsky, Yossi Elkrief
http://developer.android.com/guide/components/fragments.html
Content
● What is a Fragment?
● Design
● Backward compatibility
● Lifecycle
● Managing
● Transaction
● Best practices
● DialogFragment
Fragment ?
Fragment = partial behavior of user interface
● Modular design to different screen orientations and
   multiple screen sizes
● Multiple fragments can reside in a single activity
● Reuse a fragment in multiple activities
● Has its own lifecycle
Design
● Fragments were introduced in Android 3.0
● Support more dynamic and flexible UI
  designs on large screens
● Allow designs without the need to manage
  complex changes to the view hierarchy
● What about previous versions of Android?
Backward compatibility
● Compatibility Package
● Targeting 1.6 (API 4) or later
● APIs work almost exactly the same as their
  counterparts in the latest Android platform
   ○ android.support.v4.app.FragmentActivity
   ○ android.support.v4.app.Fragment
   ○ android.support.v4.app.FragmentManager
   ○ android.support.v4.app.FragmentTransaction
Lifecycle
Adding Fragments Via layout
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.
com/apk/res/android"
   android:orientation="horizontal"
   android:layout_width="match_parent"
   android:layout_height="match_parent">
   <fragment android:name="com.gdg.FirstFragment"
       android:id="@+id/list"
       android:layout_weight="1"
       android:layout_width="0dp"
       android:layout_height="match_parent" />
   <fragment android:name="com.gdg.SecondFragment"
       android:id="@+id/viewer"
       android:layout_weight="2"
       android:layout_width="0dp"
       android:layout_height="match_parent" />
</LinearLayout>

Identifiers : id, tag, id of fragment container.
Adding Fragments Via Code
● specify a ViewGroup in which to place the
  fragment
● using the add() method, specifying the
  fragment to add and the view in which to
  insert
FragmentManager fragmentManager = getFragmentManager()
FragmentTransaction fragmentTransaction = fragmentManager.
beginTransaction();

ExampleFragment fragment = new ExampleFragment();
fragmentTransaction.add(R.id.fragment_container,
fragment);
fragmentTransaction.commit();
Adding Fragments without a UI

● provide a background behavior for the
  activity without presenting additional UI
● it does not receive a call to onCreateView()

ExampleFragment fragment = new ExampleFragment();
fragmentTransaction.add(fragment, "FragmentTag");
fragmentTransaction.commit();


● get the fragment from the activity later, you
  need to use findFragmentByTag()
Managing
● FragmentManager
  ○ getFragmentManager()
    ■ findFragmentById()
    ■ findFragmentByTag()
    ■ popBackStack()
    ■ addOnBackStackChangedListener()
Handling fragments example
● FragmentManager + FragmentTransaction
● Usage:
// Create new fragment and transaction
Fragment newFragment = new ExampleFragment ();
FragmentTransaction transaction = getFragmentManager().beginTransaction ();
// Replace whatever is in the fragment_container view with this fragment,
// and add the transaction to the back stack
transaction .replace(R.id.fragment_container , newFragment );
transaction .addToBackStack (null);
// Commit the transaction
transaction .commit();
Fragments Special care

● run-time configuration change can cause the
  activity automatically re-instantiate existing
  fragments.
     // Tell the framework to try to keep this fragment around
// during a configuration change.
setRetainInstance(true);

● Check your Bundle.
public void onCreate(Bundle savedInstanceState) {

    if (savedInstanceState == null){
          Do Create the Fragment
    }else{
          Activity was recreated
    }
}
Best Practices


● Fragment Interfaces Invoke Activity

  ○ Use event callbacks.

● Activity as commutator
DialogFragment

● showDialog / dismissDialog - deprecated
● floating on top of its activity's window
● v4 support library (for backward compatibility
  on pre-Honeycomb devices)
DialogFragment - class
import android.support.v4.app.DialogFragment;
// ...
public class EditNameDialog extends DialogFragment {
       private EditText mEditText;
       public EditNameDialog() {
             // Empty constructor required for DialogFragment
       }
       @Override
       public View onCreateView(LayoutInflater inflater, ViewGroup container,
             Bundle savedInstanceState) {
             View view = inflater.inflate(R.layout.fragment_edit_name, container);
             mEditText = (EditText) view.findViewById(R.id.txt_your_name);
             getDialog().setTitle("Hello");

           return view;
     }
}
DialogFragment - with interface
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
      Bundle savedInstanceState) {
      View view = inflater.inflate(R.layout.fragment_edit_name, container);
      mEditText = (EditText) view.findViewById(R.id.txt_your_name);
      getDialog().setTitle("Hello");
      // Show soft keyboard automatically
      mEditText.requestFocus();
       getDialog().getWindow().setSoftInputMode(LayoutParams.SOFT_INPUT_STATE_VISIBLE);
      mEditText.setOnEditorActionListener(this); // when we press done
      return view;
}
@Override
public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
      if (EditorInfo.IME_ACTION_DONE == actionId) {
             // Return input text to activity
             EditNameDialogListener activity = (EditNameDialogListener) getActivity();
             activity.onFinishEditDialog(mEditText.getText().toString());
             this.dismiss();
             return true;
      }
      return false;
}
DialogFragment - Showing
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
// ...
public class FragmentDialogDemo extends FragmentActivity implements EditNameDialogListener {
       @Override
       public void onCreate(Bundle savedInstanceState) {
       super.onCreate(savedInstanceState);
             setContentView(R.layout.main);
             showEditDialog();
       }
       private void showEditDialog() {
             FragmentManager fm = getSupportFragmentManager();
             EditNameDialog editNameDialog = new EditNameDialog();
             editNameDialog.show(fm, "fragment_edit_name");
       }
       @Override
       public void onFinishEditDialog(String inputText) {
             Toast.makeText(this, "Hi, " + inputText, Toast.LENGTH_SHORT).show();
       }
}
Sample Fragments application




 https://github.com/MaTriXy/FragmentsGDG
Questions?




http://developer.android.com/guide/components/fragments.html

Mais conteúdo relacionado

Mais procurados

Fragmentation in android
Fragmentation in android Fragmentation in android
Fragmentation in android Esraa El Ghoul
 
Android basic 4 Navigation Drawer
Android basic 4 Navigation DrawerAndroid basic 4 Navigation Drawer
Android basic 4 Navigation DrawerEakapong Kattiya
 
Android Support Library: Using ActionBarCompat
Android Support Library: Using ActionBarCompatAndroid Support Library: Using ActionBarCompat
Android Support Library: Using ActionBarCompatcbeyls
 
Write a Google Closure Editor Plugin
Write a Google Closure Editor PluginWrite a Google Closure Editor Plugin
Write a Google Closure Editor Pluginyinhm .
 
Activities, Fragments, and Events
Activities, Fragments, and EventsActivities, Fragments, and Events
Activities, Fragments, and EventsHenry Osborne
 
Fragments In Android
Fragments In AndroidFragments In Android
Fragments In AndroidDivyaKS12
 
STYLISH FLOOR
STYLISH FLOORSTYLISH FLOOR
STYLISH FLOORABU HASAN
 
Droidcon 2011: Working with the Android source, Ronan Schwarz, Openintents
Droidcon 2011: Working with the Android source, Ronan Schwarz, OpenintentsDroidcon 2011: Working with the Android source, Ronan Schwarz, Openintents
Droidcon 2011: Working with the Android source, Ronan Schwarz, OpenintentsDroidcon Berlin
 
Understanding React hooks | Walkingtree Technologies
Understanding React hooks | Walkingtree TechnologiesUnderstanding React hooks | Walkingtree Technologies
Understanding React hooks | Walkingtree TechnologiesWalking Tree Technologies
 
Android: the Single Activity, Multiple Fragments pattern | One Activity to ru...
Android: the Single Activity, Multiple Fragments pattern | One Activity to ru...Android: the Single Activity, Multiple Fragments pattern | One Activity to ru...
Android: the Single Activity, Multiple Fragments pattern | One Activity to ru...olrandir
 

Mais procurados (15)

Fragmentation in android
Fragmentation in android Fragmentation in android
Fragmentation in android
 
Android basic 4 Navigation Drawer
Android basic 4 Navigation DrawerAndroid basic 4 Navigation Drawer
Android basic 4 Navigation Drawer
 
Android basic 2 UI Design
Android basic 2 UI DesignAndroid basic 2 UI Design
Android basic 2 UI Design
 
Android Support Library: Using ActionBarCompat
Android Support Library: Using ActionBarCompatAndroid Support Library: Using ActionBarCompat
Android Support Library: Using ActionBarCompat
 
Write a Google Closure Editor Plugin
Write a Google Closure Editor PluginWrite a Google Closure Editor Plugin
Write a Google Closure Editor Plugin
 
Activities, Fragments, and Events
Activities, Fragments, and EventsActivities, Fragments, and Events
Activities, Fragments, and Events
 
Fragments In Android
Fragments In AndroidFragments In Android
Fragments In Android
 
STYLISH FLOOR
STYLISH FLOORSTYLISH FLOOR
STYLISH FLOOR
 
Droidcon 2011: Working with the Android source, Ronan Schwarz, Openintents
Droidcon 2011: Working with the Android source, Ronan Schwarz, OpenintentsDroidcon 2011: Working with the Android source, Ronan Schwarz, Openintents
Droidcon 2011: Working with the Android source, Ronan Schwarz, Openintents
 
Android best practices
Android best practicesAndroid best practices
Android best practices
 
Android
AndroidAndroid
Android
 
Understanding React hooks | Walkingtree Technologies
Understanding React hooks | Walkingtree TechnologiesUnderstanding React hooks | Walkingtree Technologies
Understanding React hooks | Walkingtree Technologies
 
Swf2 ui
Swf2 uiSwf2 ui
Swf2 ui
 
Android in practice
Android in practiceAndroid in practice
Android in practice
 
Android: the Single Activity, Multiple Fragments pattern | One Activity to ru...
Android: the Single Activity, Multiple Fragments pattern | One Activity to ru...Android: the Single Activity, Multiple Fragments pattern | One Activity to ru...
Android: the Single Activity, Multiple Fragments pattern | One Activity to ru...
 

Semelhante a Fragments anyone

Android Best Practices
Android Best PracticesAndroid Best Practices
Android Best PracticesYekmer Simsek
 
深入淺出談Fragment
深入淺出談Fragment深入淺出談Fragment
深入淺出談Fragment毅 方
 
Tk2323 lecture 6 fragment (new)
Tk2323 lecture 6   fragment (new)Tk2323 lecture 6   fragment (new)
Tk2323 lecture 6 fragment (new)MengChun Lam
 
Data binding в массы!
Data binding в массы!Data binding в массы!
Data binding в массы!Artjoker
 
Introduction to Griffon
Introduction to GriffonIntroduction to Griffon
Introduction to GriffonJames Williams
 
Overview of Android Infrastructure
Overview of Android InfrastructureOverview of Android Infrastructure
Overview of Android InfrastructureAlexey Buzdin
 
Overview of Android Infrastructure
Overview of Android InfrastructureOverview of Android Infrastructure
Overview of Android InfrastructureC.T.Co
 
Михаил Анохин "Data binding 2.0"
Михаил Анохин "Data binding 2.0"Михаил Анохин "Data binding 2.0"
Михаил Анохин "Data binding 2.0"Fwdays
 
Thomas braun dependency-injection_with_robo_guice-presentation-final
Thomas braun dependency-injection_with_robo_guice-presentation-finalThomas braun dependency-injection_with_robo_guice-presentation-final
Thomas braun dependency-injection_with_robo_guice-presentation-finalDroidcon Berlin
 
Android Code Puzzles (DroidCon Amsterdam 2012)
Android Code Puzzles (DroidCon Amsterdam 2012)Android Code Puzzles (DroidCon Amsterdam 2012)
Android Code Puzzles (DroidCon Amsterdam 2012)Danny Preussler
 
Data binding в массы! (1.2)
Data binding в массы! (1.2)Data binding в массы! (1.2)
Data binding в массы! (1.2)Yurii Kotov
 
02 hello world - Android
02   hello world - Android02   hello world - Android
02 hello world - AndroidWingston
 
Quick Intro to Android Development
Quick Intro to Android DevelopmentQuick Intro to Android Development
Quick Intro to Android DevelopmentJussi Pohjolainen
 
"Android Data Binding в массы" Михаил Анохин
"Android Data Binding в массы" Михаил Анохин"Android Data Binding в массы" Михаил Анохин
"Android Data Binding в массы" Михаил АнохинFwdays
 
Net conf BG xamarin lecture
Net conf BG xamarin lectureNet conf BG xamarin lecture
Net conf BG xamarin lectureTsvyatko Konov
 

Semelhante a Fragments anyone (20)

Android Best Practices
Android Best PracticesAndroid Best Practices
Android Best Practices
 
深入淺出談Fragment
深入淺出談Fragment深入淺出談Fragment
深入淺出談Fragment
 
Tk2323 lecture 6 fragment (new)
Tk2323 lecture 6   fragment (new)Tk2323 lecture 6   fragment (new)
Tk2323 lecture 6 fragment (new)
 
Data binding в массы!
Data binding в массы!Data binding в массы!
Data binding в массы!
 
Introduction to Griffon
Introduction to GriffonIntroduction to Griffon
Introduction to Griffon
 
Overview of Android Infrastructure
Overview of Android InfrastructureOverview of Android Infrastructure
Overview of Android Infrastructure
 
Overview of Android Infrastructure
Overview of Android InfrastructureOverview of Android Infrastructure
Overview of Android Infrastructure
 
Михаил Анохин "Data binding 2.0"
Михаил Анохин "Data binding 2.0"Михаил Анохин "Data binding 2.0"
Михаил Анохин "Data binding 2.0"
 
Thomas braun dependency-injection_with_robo_guice-presentation-final
Thomas braun dependency-injection_with_robo_guice-presentation-finalThomas braun dependency-injection_with_robo_guice-presentation-final
Thomas braun dependency-injection_with_robo_guice-presentation-final
 
Android Code Puzzles (DroidCon Amsterdam 2012)
Android Code Puzzles (DroidCon Amsterdam 2012)Android Code Puzzles (DroidCon Amsterdam 2012)
Android Code Puzzles (DroidCon Amsterdam 2012)
 
Android gui framework
Android gui frameworkAndroid gui framework
Android gui framework
 
Data binding в массы! (1.2)
Data binding в массы! (1.2)Data binding в массы! (1.2)
Data binding в массы! (1.2)
 
02 hello world - Android
02   hello world - Android02   hello world - Android
02 hello world - Android
 
Android development
Android developmentAndroid development
Android development
 
Quick Intro to Android Development
Quick Intro to Android DevelopmentQuick Intro to Android Development
Quick Intro to Android Development
 
Android 3
Android 3Android 3
Android 3
 
What the fragments
What the fragmentsWhat the fragments
What the fragments
 
"Android Data Binding в массы" Михаил Анохин
"Android Data Binding в массы" Михаил Анохин"Android Data Binding в массы" Михаил Анохин
"Android Data Binding в массы" Михаил Анохин
 
Fragment
Fragment Fragment
Fragment
 
Net conf BG xamarin lecture
Net conf BG xamarin lectureNet conf BG xamarin lecture
Net conf BG xamarin lecture
 

Fragments anyone

  • 1. Fragments anyone? Leonid Olevsky, Yossi Elkrief http://developer.android.com/guide/components/fragments.html
  • 2. Content ● What is a Fragment? ● Design ● Backward compatibility ● Lifecycle ● Managing ● Transaction ● Best practices ● DialogFragment
  • 3. Fragment ? Fragment = partial behavior of user interface ● Modular design to different screen orientations and multiple screen sizes ● Multiple fragments can reside in a single activity ● Reuse a fragment in multiple activities ● Has its own lifecycle
  • 4. Design ● Fragments were introduced in Android 3.0 ● Support more dynamic and flexible UI designs on large screens ● Allow designs without the need to manage complex changes to the view hierarchy ● What about previous versions of Android?
  • 5. Backward compatibility ● Compatibility Package ● Targeting 1.6 (API 4) or later ● APIs work almost exactly the same as their counterparts in the latest Android platform ○ android.support.v4.app.FragmentActivity ○ android.support.v4.app.Fragment ○ android.support.v4.app.FragmentManager ○ android.support.v4.app.FragmentTransaction
  • 7. Adding Fragments Via layout <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android. com/apk/res/android" android:orientation="horizontal" android:layout_width="match_parent" android:layout_height="match_parent"> <fragment android:name="com.gdg.FirstFragment" android:id="@+id/list" android:layout_weight="1" android:layout_width="0dp" android:layout_height="match_parent" /> <fragment android:name="com.gdg.SecondFragment" android:id="@+id/viewer" android:layout_weight="2" android:layout_width="0dp" android:layout_height="match_parent" /> </LinearLayout> Identifiers : id, tag, id of fragment container.
  • 8. Adding Fragments Via Code ● specify a ViewGroup in which to place the fragment ● using the add() method, specifying the fragment to add and the view in which to insert FragmentManager fragmentManager = getFragmentManager() FragmentTransaction fragmentTransaction = fragmentManager. beginTransaction(); ExampleFragment fragment = new ExampleFragment(); fragmentTransaction.add(R.id.fragment_container, fragment); fragmentTransaction.commit();
  • 9. Adding Fragments without a UI ● provide a background behavior for the activity without presenting additional UI ● it does not receive a call to onCreateView() ExampleFragment fragment = new ExampleFragment(); fragmentTransaction.add(fragment, "FragmentTag"); fragmentTransaction.commit(); ● get the fragment from the activity later, you need to use findFragmentByTag()
  • 10. Managing ● FragmentManager ○ getFragmentManager() ■ findFragmentById() ■ findFragmentByTag() ■ popBackStack() ■ addOnBackStackChangedListener()
  • 11. Handling fragments example ● FragmentManager + FragmentTransaction ● Usage: // Create new fragment and transaction Fragment newFragment = new ExampleFragment (); FragmentTransaction transaction = getFragmentManager().beginTransaction (); // Replace whatever is in the fragment_container view with this fragment, // and add the transaction to the back stack transaction .replace(R.id.fragment_container , newFragment ); transaction .addToBackStack (null); // Commit the transaction transaction .commit();
  • 12. Fragments Special care ● run-time configuration change can cause the activity automatically re-instantiate existing fragments. // Tell the framework to try to keep this fragment around // during a configuration change. setRetainInstance(true); ● Check your Bundle. public void onCreate(Bundle savedInstanceState) { if (savedInstanceState == null){ Do Create the Fragment }else{ Activity was recreated } }
  • 13. Best Practices ● Fragment Interfaces Invoke Activity ○ Use event callbacks. ● Activity as commutator
  • 14. DialogFragment ● showDialog / dismissDialog - deprecated ● floating on top of its activity's window ● v4 support library (for backward compatibility on pre-Honeycomb devices)
  • 15. DialogFragment - class import android.support.v4.app.DialogFragment; // ... public class EditNameDialog extends DialogFragment { private EditText mEditText; public EditNameDialog() { // Empty constructor required for DialogFragment } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_edit_name, container); mEditText = (EditText) view.findViewById(R.id.txt_your_name); getDialog().setTitle("Hello"); return view; } }
  • 16. DialogFragment - with interface @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_edit_name, container); mEditText = (EditText) view.findViewById(R.id.txt_your_name); getDialog().setTitle("Hello"); // Show soft keyboard automatically mEditText.requestFocus(); getDialog().getWindow().setSoftInputMode(LayoutParams.SOFT_INPUT_STATE_VISIBLE); mEditText.setOnEditorActionListener(this); // when we press done return view; } @Override public boolean onEditorAction(TextView v, int actionId, KeyEvent event) { if (EditorInfo.IME_ACTION_DONE == actionId) { // Return input text to activity EditNameDialogListener activity = (EditNameDialogListener) getActivity(); activity.onFinishEditDialog(mEditText.getText().toString()); this.dismiss(); return true; } return false; }
  • 17. DialogFragment - Showing import android.support.v4.app.FragmentActivity; import android.support.v4.app.FragmentManager; // ... public class FragmentDialogDemo extends FragmentActivity implements EditNameDialogListener { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); showEditDialog(); } private void showEditDialog() { FragmentManager fm = getSupportFragmentManager(); EditNameDialog editNameDialog = new EditNameDialog(); editNameDialog.show(fm, "fragment_edit_name"); } @Override public void onFinishEditDialog(String inputText) { Toast.makeText(this, "Hi, " + inputText, Toast.LENGTH_SHORT).show(); } }
  • 18. Sample Fragments application https://github.com/MaTriXy/FragmentsGDG