Monday 16 May 2016

Android Fragment Lifecycle

A Fragment represents a behavior 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.

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. When you perform such a fragment transaction, you can also add it to a back stack that's managed by the activity--each back stack entry in the activity is a record of the fragment transaction that occurred. The back stack allows the user to reverse a fragment transaction (navigate backwards), by pressing the Back button.

When you add a fragment as a part of your activity layout, it lives in a ViewGroup inside the activity's view hierarchy and the fragment defines its own view layout. You can insert a fragment into your activity layout by declaring the fragment in the activity's layout file, as a <fragment> element, or from your application code by adding it to an existing ViewGroup. However, a fragment is not required to be a part of the activity layout; you may also use a fragment without its own UI as an invisible worker for the activity.

Design Philosophy

Android introduced fragments in Android 3.0 (API level 11), primarily to support more dynamic and flexible UI designs on large screens, such as tablets. Because a tablet's screen is much larger than that of a handset, there's more room to combine and interchange UI components. Fragments allow such designs without the need for you to manage complex changes to the view hierarchy. By dividing the layout of an activity into fragments, you become able to modify the activity's appearance at runtime and preserve those changes in a back stack that's managed by the activity.

For example, a news application can use one fragment to show a list of articles on the left and another fragment to display an article on the right—both fragments appear in one activity, side by side, and each fragment has its own set of lifecycle callback methods and handle their own user input events. Thus, instead of using one activity to select an article and another activity to read the article, the user can select an article and read it all within the same activity.

Creating a Fragment
To create a fragment, you must create a subclass of Fragment (or an existing subclass of it). The Fragment class has code that looks a lot like an Activity. It contains callback methods similar to an activity, such as onCreate(), onStart(), onPause(), and onStop(). In fact, if you're converting an existing Android application to use fragments, you might simply move code from your activity's callback methods into the respective callback methods of your fragment.

Usually, you should implement at least the following lifecycle methods:

onCreate()
The system calls this when creating the fragment. Within your implementation, you should initialize essential components of the fragment that you want to retain when the fragment is paused or stopped, then resumed.
onCreateView()
The system calls this when it's time for the fragment to draw its user interface for the first time. To draw a UI for your fragment, you must return a View from this method that is the root of your fragment's layout. You can return null if the fragment does not provide a UI.
onPause()
The system calls this method as the first indication that the user is leaving the fragment (though it does not always mean the fragment is being destroyed). This is usually where you should commit any changes that should be persisted beyond the current user session (because the user might not come back).

There are also a few subclasses that you might want to extend, instead of the base Fragment class:

DialogFragment
Displays a floating dialog. Using this class to create a dialog is a good alternative to using the dialog helper methods in the Activity class, because you can incorporate a fragment dialog into the back stack of fragments managed by the activity, allowing the user to return to a dismissed fragment.

ListFragment
Displays a list of items that are managed by an adapter (such as a SimpleCursorAdapter), similar to ListActivity. It provides several methods for managing a list view, such as the onListItemClick() callback to handle click events.

PreferenceFragment
Displays a hierarchy of Preference objects as a list, similar to PreferenceActivity. This is useful when creating a "settings" activity for your application.
Adding a user interface

To provide a layout for a fragment, you must implement the onCreateView() callback method, which the Android system calls when it's time for the fragment to draw its layout. Your implementation of this method must return a View that is the root of your fragment's layout.

public static class ExampleFragment extends Fragment {
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.example_fragment, container, false);
    }
}


Adding a fragment to an activity

Usually, a fragment contributes a portion of UI to the host activity, which is embedded as a part of the activity's overall view hierarchy. There are two ways you can add a fragment to the activity layout:

Declare the fragment inside the activity's layout file.

In this case, you can specify layout properties for the fragment as if it were a view. For example, here's the layout file for an activity with two fragments:

<?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.example.news.ArticleListFragment"
            android:id="@+id/list"
            android:layout_weight="1"
            android:layout_width="0dp"
            android:layout_height="match_parent" />
    <fragment android:name="com.example.news.ArticleReaderFragment"
            android:id="@+id/viewer"
            android:layout_weight="2"
            android:layout_width="0dp"
            android:layout_height="match_parent" />
</LinearLayout>

The android:name attribute in the <fragment> specifies the Fragment class to instantiate in the layout.
When the system creates this activity layout, it instantiates each fragment specified in the layout and calls the onCreateView() method for each one, to retrieve each fragment's layout. The system inserts the View returned by the fragment directly in place of the <fragment> element.

Note: Each fragment requires a unique identifier that the system can use to restore the fragment if the activity is restarted (and which you can use to capture the fragment to perform transactions, such as remove it). There are three ways to provide an ID for a fragment:

Supply the android:id attribute with a unique ID.

Supply the android:tag attribute with a unique string.

If you provide neither of the previous two, the system uses the ID of the container view.
Or, programmatically add the fragment to an existing ViewGroup.

At any time while your activity is running, you can add fragments to your activity layout. You simply need to specify a ViewGroup in which to place the fragment.

To make fragment transactions in your activity (such as add, remove, or replace a fragment), you must use APIs from FragmentTransaction. You can get an instance of FragmentTransaction from your Activity like this:

FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();

You can then add a fragment using the add() method, specifying the fragment to add and the view in which to insert it. For example:

ExampleFragment fragment = new ExampleFragment();
fragmentTransaction.add(R.id.fragment_container, fragment);
fragmentTransaction.commit();

The first argument passed to add() is the ViewGroup in which the fragment should be placed, specified by resource ID, and the second parameter is the fragment to add.
Once you've made your changes with FragmentTransaction, you must call commit() for the changes to take effect.

Handling the Fragment Lifecycle

onAttach() :This method will be called first, even before onCreate(), letting us know that your fragment has been attached to an activity. You are passed the Activity that will host your fragment.

onCreateView() : The system calls this callback when it’s time for the fragment to draw its UI for the first time. To draw a UI for the fragment, a View component must be returned from this method which is the root of the fragment’s layout. We can return null if the fragment does not provide a UI.

onViewCreated() : This will be called after onCreateView(). This is particularly useful when inheriting the onCreateView() implementation but we need to configure the resulting views, such as with a ListFragment and when to set up an adapter.

onActivityCreated() :This will be called after onCreate() and onCreateView(), to indicate that the activity’s onCreate() has completed. If there is something that’s needed to be initialised in the fragment that depends upon the activity’s onCreate() having completed its work then onActivityCreated() can be used for that initialisation work.

onStart() : The onStart() method is called once the fragment gets visible.

onPause() : The system calls this method as the first indication that the user is leaving the fragment. This is usually where you should commit any changes that should be persisted beyond the current user session

onStop() : Fragment going to be stopped by calling onStop()

onDestroyView() : It’s called before onDestroy(). This is the counterpart to onCreateView() where we set up the UI. If there are things that are needed to be cleaned up specific to the UI, then that logic can be put up in onDestroyView().

onDestroy() : onDestroy() called to do final clean up of the fragment’s state but Not guaranteed to be called by the Android platform.

onDetach() : It’s called after onDestroy(), to notify that the fragment has been disassociated from its hosting activity.










8 comments:

  1. Your blog has given me that thing which I never expect to get from all over the websites. Nice post guys!

    ReplyDelete
  2. This comment has been removed by the author.

    ReplyDelete
  3. https://elnaga7.com/%D8%B4%D8%B1%D9%83%D8%A9-%D9%83%D8%B4%D9%81-%D8%AA%D8%B3%D8%B1%D8%A8%D8%A7%D8%AA-%D8%A7%D9%84%D9%85%D9%8A%D8%A7%D9%87-%D8%A8%D8%A7%D9%84%D8%B1%D9%8A%D8%A7%D8%B6/

    ReplyDelete


  4. تعد المكيفات من اهم الوسائل التكنولوجية الحديثة التي مكنت الإنسان من التعايش في البيئة الصحراوية بسهولة، من هنا كان أمر صيانتها وتنظيفها ذا أهمية كبيرة، فلا تستطع الأسر أن في فترات الصيف والحر؛ من هنا كان أمر الاستعانة بـ
    شركة تنظيف مكيفات بالاحساء

    شركة الرحمة لتنظيف جميع أنواع المكيفات بأحدث طرق إزالة الأتربة والعوالق مهما مر عليها الوقت، الشركة توفر العمالة المتدربة على جميع أعمال التنظيف والصيانة وغسيل المكيفات بالدمام بكافة أنواعها، شركة نالت إعجاب جميع العملاء من كل مدن المملكة العربية السعودية، يمكنك التأكد من مصداقية الشركة عن طريق متابعة صفحة شركة الرحمة لتنظيف وغسيل وصيانة المكيفات بالدمام.
    شركة تنظيف مكيفات بالخبر

    وذلك من أجل الوصول إلى خدمات احترافية غير متوفرة لدى جميع شركات تنظيف المكيفات بالدمام الأخرى. تسعى شركة تركيب مكيفات بالدمام على العمل على راحة جميع العملاء لأنها تعرف المعاناة التي سوف ينالها العميل عند توقف المكيف ويقل حركته بسبب حاجته إلى التنظيف

    شركة تنظيف مكيفات بالدمام

    شركة تنظيف مكيفات بالجبيل

    ReplyDelete
  5. لذلك خصصت شركة تنظيف مكيفات بغرب الدمام مجموعة من الأنظمة والبرامج التي تسير على نهجها من اجل تنظيف مختلف أنواع المكيفات لضمان تشغيل المكيف بكفاءة عالية. نساعد جميع العملاء الذين لديهم انخفاض وقلة في غاز الفريون الذي يعبأ داخل المكيفات والمسئول عن البرودة التي يحدثها المكيف في المكان.
    فنحن بفضل الله نقوم بتعبئة هذا الغاز داخل مختلف أنواع المكيفات سواء كان المكيف الهندي أو المكيف الصيني أو المكيف التركي أو المكيف الأمريكي وغيره من الماركات الممتازة كما أننا نعرف المقدار الذي يسمح به كل مكيف من أجل تعبئته بشكل جيد لضمان استمرار عمله بدون تلف أو توقف بعد التعامل مع شركة تنظيف مكيفات في الدمام. وخلال القيام بهذه الخطوات لابد من ضخ المياه بحرص شديد تجنبًا لتلامس البوردة والأسلاك الكهربائية المتواجدة داخل المكيف

    شركة تنظيف مكيفات بالقطيف

    لمزيد من خدمتنا الاخرى

    شركة تنظيف بالدمام

    شركة تنظيف منازل بالدمام

    شركة تنظيف خزانات بجازان

    شركة تنظيف مسابح بالرياض

    شركة شراء اثاث مستعمل بالرياض

    ReplyDelete
  6. شركة تعقيم بالقصيم fi alfatrat al'akhirat wabaed al'iintishar alkabir lifayrus kuruna fi kafat 'anha' alealam , fa'asbahat eamaliaat albahth ean sharikat taeqim bialqasim kathiratan min 'ajl eamaliaat altaeqim lilmanazil walshuqaq walfilaat شركة مكافحة الحمام بالقصيم alkathir min alsukaan fi manazil buridat yueanun min kathrat alhamam alnaajim ean kathrat alhamaamat bial'iidafat 'iilaa alraayihat alkarihat شركة مكافحة حشرات بالقصيم sharikat mukafahat hasharat bialqasim tuqadim al'iibadat walnihayiyat lilsarasir sawa' kanat alzaahif minha 'aw altaayir , tilk alhasharat dhat almazhar almuqaziz waltaathir alsalbii ealaa alsihat lima tabuthuh min jarathim wamikrubat bialtaeamif'iidha lahazna 'akthar makan tatajamae fih شركة تنظيف مكيفات بالقصيم tuetabar eamaliat mutakamilat eamaliat altanzif alati taqum biha eamaliat altanzif alati taqum biha alsharikat , hayth yatajahaluha hayth yatarakam alghubar dakhil almarawih walmurashahat waldawaghit wabayanatihi شركة تنظيف منازل بالقصيم sharikat tanzif bialqasim almutakhasisat fi tanzif alshuqaq walfilal walmakatib walsharikat altijariat aleamilat fi majal aleamal altijarii fi majal altanzif bitadribina bialtariqat alhadithat fi majal alnazafa ... nadman jawdat alkhidmat wanaqum 'asafaha bi'asrae al'asear fi alnazafat wanaqum bitanzifiha

    ReplyDelete