banner



How To Update Initial Activity Page After Updating The Adapter

Overview

A fragment is a reusable course implementing a portion of an activity. A Fragment typically defines a part of a user interface. Fragments must be embedded in activities; they cannot run independently of activities.

Fragments

Agreement Fragments

Here are the important things to understand most fragments:

  • A Fragment is a combination of an XML layout file and a java class much like an Activity.
  • Using the support library, fragments are supported back to all relevant Android versions.
  • Fragments encapsulate views and logic then that it is easier to reuse within activities.
  • Fragments are standalone components that can contain views, events and logic.

Within a fragment-oriented compages, activities become navigational containers that are primarily responsible for navigation to other activities, presenting fragments and passing information.

Importance of Fragments

There are many use cases for fragments but the well-nigh common utilize cases include:

  • Reusing View and Logic Components - Fragments enable re-utilise of parts of your screen including views and upshot logic over and over in unlike ways across many disparate activities. For example, using the aforementioned list beyond unlike data sources inside an app.
  • Tablet Back up - Oft inside apps, the tablet version of an activeness has a substantially different layout from the phone version which is different from the TV version. Fragments enable device-specific activities to reuse shared elements while too having differences.
  • Screen Orientation - Oftentimes within apps, the portrait version of an activity has a substantially unlike layout from the landscape version. Fragments enable both orientations to reuse shared elements while also having differences.

Organizing your Code

Inside a fragment-heavy app, we need to remember to organize our code co-ordinate to architectural best practices. Within of an app which uses fragments extensively, we need to continue in mind that the role of an activeness shifts.

Activities are navigation controllers primarily responsible for:

  • Navigation to other activities through intents.
  • Presenting navigational components such as the navigation drawer or the viewpager.
  • Hiding and showing relevant fragments using the fragment manager.
  • Receiving data from intents and passing data between fragments.

Fragments are content controllers and comprise near views, layouts, and event logic including:

  • Layouts and views displaying relevant app content.
  • Consequence handling logic associated with relevant views.
  • View land management logic such as visibility or error handling.
  • Triggering of network request through a client object.
  • Retrieval and storage of data from persistence through model objects.

To reiterate, in a fragment-based architecture, the activities are for navigation and the fragments are for views and logic.

Usage

Defining a Fragment

A fragment, like an activity, has an XML layout file and a Java class that represents the Fragment controller.

The XML layout file is only similar any other layout file, and can be named fragment_foo.xml. Think of them every bit a partial (re-usable) action:

                      <?xml version="ane.0" encoding="utf-eight"?>            <LinearLayout            xmlns:android=            "http://schemas.android.com/apk/res/android"            android:layout_width=            "match_parent"            android:layout_height=            "match_parent"            android:orientation=            "vertical"            >            <TextView            android:id=            "@+id/textView1"            android:layout_width=            "wrap_content"            android:layout_height=            "wrap_content"            android:text=            "TextView"            />            <Push            android:id=            "@+id/button1"            android:layout_width=            "wrap_content"            android:layout_height=            "wrap_content"            android:text=            "Push button"            />            </LinearLayout>                  

The Java controller for a fragment looks like:

                      import            androidx.fragment.app.Fragment            ;            public            class            FooFragment            extends            Fragment            {            // The onCreateView method is chosen when Fragment should create its View object bureaucracy,            // either dynamically or via XML layout inflation.                        @Override            public            View            onCreateView            (            LayoutInflater            inflater            ,            ViewGroup            parent            ,            Package            savedInstanceState            )            {            // Defines the xml file for the fragment            render            inflater            .            inflate            (            R            .            layout            .            fragment_foo            ,            parent            ,            false            );            }            // This issue is triggered shortly after onCreateView().            // Any view setup should occur here.  E.g., view lookups and attaching view listeners.            @Override            public            void            onViewCreated            (            View            view            ,            Bundle            savedInstanceState            )            {            // Setup any handles to view objects here            // EditText etFoo = (EditText) view.findViewById(R.id.etFoo);            }            }                  

Embedding a Fragment in an Action

There are ii ways to add together a fragment to an action: dynamically using Coffee and statically using XML.

Before embedding a "back up" fragment in an Activity make sure the Activity is changed to extend from FragmentActivity or AppCompatActivity which adds support for the fragment director to all Android versions. Any activity using fragments should make sure to extend from FragmentActivity or AppCompatActivity:

                      import            androidx.appcompat.app.AppCompatActivity            ;            public            course            MainActivity            extends            AppCompatActivity            {            // ...            }                  

Statically

To add the fragment statically, simply embed the fragment in the activity'south xml layout file:

                      <?xml version="1.0" encoding="utf-8"?>            <LinearLayout            xmlns:android=            "http://schemas.android.com/apk/res/android"            android:layout_width=            "match_parent"            android:layout_height=            "match_parent"            android:orientation=            "vertical"            >            <fragment            android:name=            "com.example.android.FooFragment"            android:id=            "@+id/fooFragment"            android:layout_width=            "match_parent"            android:layout_height=            "match_parent"            />            </LinearLayout>                  

Note:

  • You will probable demand to change the path for FooFragment based on your project setup.
  • You cannot replace a fragment defined statically in the layout file via a FragmentTransaction. You tin can only supplant fragments that you added dynamically.

Dynamically

The second style is by calculation the fragment dynamically in Coffee using the FragmentManager. The FragmentManager course and the FragmentTransaction course allow yous to add, remove and supersede fragments in the layout of your activity at runtime.

In this case, you lot desire to add a "placeholder" container (ordinarily a FrameLayout) to your activity where the fragment is inserted at runtime:

                      <?xml version="1.0" encoding="utf-viii"?>            <LinearLayout            xmlns:android=            "http://schemas.android.com/apk/res/android"            android:layout_width=            "match_parent"            android:layout_height=            "match_parent"            android:orientation=            "vertical"            >            <FrameLayout            android:id=            "@+id/your_placeholder"            android:layout_width=            "match_parent"            android:layout_height=            "match_parent"            >            </FrameLayout>            </LinearLayout>                  

and and so yous tin use the FragmentManager to create a FragmentTransaction which allows us to add fragments to the FrameLayout at runtime:

                      // Begin the transaction            FragmentTransaction            ft            =            getSupportFragmentManager            ().            beginTransaction            ();            // Replace the contents of the container with the new fragment            ft            .            replace            (            R            .            id            .            your_placeholder            ,            new            FooFragment            ());            // or ft.add(R.id.your_placeholder, new FooFragment());            // Complete the changes added to a higher place            ft            .            commit            ();                  

If the fragment should always be within the activity, use XML to statically add the fragment just in more circuitous cases be sure to use the Coffee-based approach.

Fragment Lifecycle

Fragment has many methods which can be overridden to plug into the lifecycle (similar to an Activity):

  • onAttach() is called when a fragment is connected to an activity.
  • onCreate() is called to do initial cosmos of the fragment.
  • onCreateView() is called past Android once the Fragment should inflate a view.
  • onViewCreated() is called after onCreateView() and ensures that the fragment's root view is not-null. Any view setup should happen here. E.g., view lookups, attaching listeners.
  • onActivityCreated() is chosen when host activity has completed its onCreate() method.
  • onStart() is chosen once the fragment is gear up to be displayed on screen.
  • onResume() - Classify "expensive" resources such every bit registering for location, sensor updates, etc.
  • onPause() - Release "expensive" resources. Commit any changes.
  • onDestroyView() is chosen when fragment's view is beingness destroyed, just the fragment is even so kept around.
  • onDestroy() is called when fragment is no longer in apply.
  • onDetach() is called when fragment is no longer continued to the activity.

The lifecycle execution order is mapped out below:

lifecycle

The most common ones to override are onCreateView which is in almost every fragment to setup the inflated view, onCreate for whatsoever data initialization and onActivityCreated used for setting upward things that can only take identify once the Action has been fully created.

Here's an case of how you might use the various fragment lifecycle events:

                      public            form            SomeFragment            extends            Fragment            {            ThingsAdapter            adapter            ;            FragmentActivity            listener            ;            // This upshot fires 1st, before creation of fragment or any views            // The onAttach method is called when the Fragment instance is associated with an Activeness.                        // This does not mean the Activity is fully initialized.            @Override            public            void            onAttach            (            Context            context            )            {            super            .            onAttach            (            context            );            if            (            context            instanceof            Activity            ){            this            .            listener            =            (            FragmentActivity            )            context            ;            }            }            // This event fires 2nd, earlier views are created for the fragment            // The onCreate method is called when the Fragment instance is being created, or re-created.            // Utilise onCreate for any standard setup that does non require the activity to exist fully created            @Override            public            void            onCreate            (            Bundle            savedInstanceState            )            {            super            .            onCreate            (            savedInstanceState            );            ArrayList            <            Thing            >            things            =            new            ArrayList            <            Thing            >();            adapter            =            new            ThingsAdapter            (            getActivity            (),            things            );            }            // The onCreateView method is called when Fragment should create its View object hierarchy,            // either dynamically or via XML layout inflation.                        @Override            public            View            onCreateView            (            LayoutInflater            inflater            ,            ViewGroup            parent            ,            Parcel            savedInstanceState            )            {            return            inflater            .            inflate            (            R            .            layout            .            fragment_some            ,            parent            ,            faux            );            }            // This effect is triggered before long subsequently onCreateView().            // onViewCreated() is only chosen if the view returned from onCreateView() is non-cypher.            // Any view setup should occur here.  Due east.g., view lookups and attaching view listeners.            @Override            public            void            onViewCreated            (            View            view            ,            Bundle            savedInstanceState            )            {            super            .            onViewCreated            (            view            ,            savedInstanceState            );            ListView            lv            =            (            ListView            )            view            .            findViewById            (            R            .            id            .            lvSome            );            lv            .            setAdapter            (            adapter            );            }            // This method is called when the fragment is no longer connected to the Activity            // Any references saved in onAttach should be nulled out here to prevent retentivity leaks.                        @Override            public            void            onDetach            ()            {            super            .            onDetach            ();            this            .            listener            =            null            ;            }            // This method is called later on the parent Activity's onCreate() method has completed.            // Accessing the view hierarchy of the parent action must be washed in the onActivityCreated.            // At this signal, it is safe to search for activity View objects by their ID, for example.            @Override            public            void            onActivityCreated            (            Bundle            savedInstanceState            )            {            super            .            onActivityCreated            (            savedInstanceState            );            }            }                  

Refer to this detailed lifecycle chart to view the lifecycle of a fragment more visually.

Looking Up a Fragment Example

Oft we need to lookup or find a fragment instance within an activity layout file. There are a few methods for looking up an existing fragment example:

  1. ID - Lookup a fragment by calling findFragmentById on the FragmentManager
  2. Tag - Lookup a fragment past calling findFragmentByTag on the FragmentManager
  3. Pager - Lookup a fragment by calling getRegisteredFragment on a PagerAdapter (non function of the Android APIs but there is a custom implementation hither https://stackoverflow.com/a/30594487)

Each method is outlined in more detail below.

Finding Fragment Past ID

If the fragment was statically embedded in the XML within an activity and given an android:id such equally fragmentDemo and so we can lookup this fragment by id past calling findFragmentById on the FragmentManager:

                      public            class            MainActivity            extends            AppCompatActivity            {            @Override            public            void            onCreate            (            Bundle            savedInstanceState            )            {            super            .            onCreate            (            savedInstanceState            );            if            (            savedInstanceState            ==            nada            )            {            DemoFragment            fragmentDemo            =            (            DemoFragment            )            getSupportFragmentManager            ().            findFragmentById            (            R            .            id            .            fragmentDemo            );            }            }            }                  

Finding Fragment By Tag

If the fragment was dynamically added at runtime within an activity then nosotros tin can lookup this fragment past tag by calling findFragmentByTag on the FragmentManager:

                      public            form            MainActivity            extends            AppCompatActivity            {            @Override            public            void            onCreate            (            Parcel            savedInstanceState            )            {            super            .            onCreate            (            savedInstanceState            );            if            (            savedInstanceState            ==            null            )            {            // Permit'south first dynamically add a fragment into a frame container            getSupportFragmentManager            ().            beginTransaction            ().            supersede            (            R            .            id            .            flContainer            ,            new            DemoFragment            (),            "SOMETAG"            ).            commit            ();            // Now afterward we tin can lookup the fragment by tag            DemoFragment            fragmentDemo            =            (            DemoFragment            )            getSupportFragmentManager            ().            findFragmentByTag            (            "SOMETAG"            );            }            }            }                  

Finding Fragment Within Pager

If the fragment was dynamically added at runtime within an activity into a ViewPager using a FragmentPagerAdapter and then we can lookup the fragment past upgrading to a SmartFragmentStatePagerAdapter as described in the ViewPager guide. Now with the adapter in place, we can also easily access any fragments within the ViewPager using getRegisteredFragment:

                      // returns kickoff Fragment item within the pager            adapterViewPager            .            getRegisteredFragment            (            0            );                  

Note that the ViewPager loads the fragment instances lazily similar to the a ListView recycling items every bit they appear on screen. If you lot attempt to access a fragment that is not on screen, the lookup will render null.

Communicating with Fragments

Fragments should generally only communicate with their direct parent activity. Fragments communicate through their parent activity allowing the activity to manage the inputs and outputs of information from that fragment coordinating with other fragments or activities. Call up of the Activity as the controller managing all interaction with each of the fragments contained within.

A few exceptions to this are dialog fragments presented from within another fragment or nested child fragments. Both of these cases are situations where a fragment has nested child fragments and that are therefore immune to communicate upwards to their parent (which is a fragment).

The important thing to go along in mind is that fragments should not directly communicate with each other and should mostly only communicate with their parent activity. Fragments should be modular, standalone and reusable components. The fragments allow their parent action to reply to intents and callbacks in almost cases.

There are three ways a fragment and an activity tin communicate:

  1. Parcel - Activity tin can construct a fragment and set arguments
  2. Methods - Action can call methods on a fragment case
  3. Listener - Fragment tin fire listener events on an activity via an interface

In other words, communication should by and large follow these principles:

  • Activities tin can initialize fragments with data during structure
  • Activities can pass information to fragments using methods on the fragment instance
  • Fragments can communicate upwardly to their parent action using an interface and listeners
  • Fragments should pass data to other fragments only routed through their parent activity
  • Fragments tin pass information to and from dialog fragments as outlined hither
  • Fragments can contain nested child fragments as outlined hither

Fragment with Arguments

In certain cases, your fragment may want to take sure arguments. A mutual blueprint is to create a static newInstance method for creating a Fragment with arguments. This is because a Fragment must have only a constructor with no arguments. Instead, we desire to use the setArguments method such as:

                      public            class            DemoFragment            extends            Fragment            {            // Creates a new fragment given an int and championship            // DemoFragment.newInstance(5, "Howdy");            public            static            DemoFragment            newInstance            (            int            someInt            ,            String            someTitle            )            {            DemoFragment            fragmentDemo            =            new            DemoFragment            ();            Bundle            args            =            new            Packet            ();            args            .            putInt            (            "someInt"            ,            someInt            );            args            .            putString            (            "someTitle"            ,            someTitle            );            fragmentDemo            .            setArguments            (            args            );            return            fragmentDemo            ;            }            }                  

This sets certain arguments into the Fragment for later access within onCreate. You lot can access the arguments after by using:

                      public            class            DemoFragment            extends            Fragment            {            @Override            public            void            onCreate            (            Bundle            savedInstanceState            )            {            super            .            onCreate            (            savedInstanceState            );            // Get dorsum arguments            int            SomeInt            =            getArguments            ().            getInt            (            "someInt"            ,            0            );            Cord            someTitle            =            getArguments            ().            getString            (            "someTitle"            ,            ""            );            }            }                  

Now we tin can load a fragment dynamically in an Activity with:

                      // Within the activity            FragmentTransaction            ft            =            getSupportFragmentManager            ().            beginTransaction            ();            DemoFragment            fragmentDemo            =            DemoFragment            .            newInstance            (            5            ,            "my title"            );            ft            .            replace            (            R            .            id            .            your_placeholder            ,            fragmentDemo            );            ft            .            commit            ();                  

This blueprint makes passing arguments to fragments for initialization fairly straightforward.

Fragment Methods

If an activity needs to make a fragment perform an action after initialization, the easiest fashion is by having the activity invoke a method on the fragment case. In the fragment, add a method:

                      public            class            DemoFragment            extends            Fragment            {            public            void            doSomething            (            String            param            )            {            // do something in fragment            }            }                  

and and so in the activity, get access to the fragment using the fragment manager and call the method:

                      public            class            MainActivity            extends            AppCompatActivity            {            @Override            public            void            onCreate            (            Bundle            savedInstanceState            )            {            super            .            onCreate            (            savedInstanceState            );            DemoFragment            fragmentDemo            =            (            DemoFragment            )            getSupportFragmentManager            ().            findFragmentById            (            R            .            id            .            fragmentDemo            );            fragmentDemo            .            doSomething            (            "some param"            );            }            }                  

and and so the activity can communicate directly with the fragment by invoking this method.

Fragment Listener

If a fragment needs to communicate events to the activity, the fragment should ascertain an interface as an inner type and require that the action must implement this interface:

                      import            androidx.fragment.app.Fragment            ;            public            course            MyListFragment            extends            Fragment            {            // ...            // Define the listener of the interface blazon            // listener will the activity instance containing fragment            individual            OnItemSelectedListener            listener            ;            // Ascertain the events that the fragment will employ to communicate            public            interface            OnItemSelectedListener            {            // This tin can be any number of events to be sent to the activity            public            void            onRssItemSelected            (            String            link            );            }            // Shop the listener (activity) that will have events fired once the fragment is attached            @Override            public            void            onAttach            (            Context            context            )            {            super            .            onAttach            (            context            );            if            (            context            instanceof            OnItemSelectedListener            )            {            listener            =            (            OnItemSelectedListener            )            context            ;            }            else            {            throw            new            ClassCastException            (            context            .            toString            ()            +            " must implement MyListFragment.OnItemSelectedListener"            );            }            }            // Now we can fire the issue when the user selects something in the fragment            public            void            onSomeClick            (            View            v            )            {            listener            .            onRssItemSelected            (            "some link"            );            }            }                  

and then in the activity nosotros accept to implement the OnItemSelectedListener listener:

                      import            androidx.appcompat.app.AppCompatActivity            ;            // Activity implements the fragment listener to handle events            public            grade            RssfeedActivity            extends            AppCompatActivity            implements            MyListFragment            .            OnItemSelectedListener            {            // Tin be whatever fragment, `DetailFragment` is just an example            DetailFragment            fragment            ;            @Override            protected            void            onCreate            (            Bundle            savedInstanceState            )            {            super            .            onCreate            (            savedInstanceState            );            setContentView            (            R            .            layout            .            activity_rssfeed            );            // Become admission to the detail view fragment by id            fragment            =            (            DetailFragment            )            getSupportFragmentManager            ()            .            findFragmentById            (            R            .            id            .            detailFragment            );            }            // Now we can define the action to take in the action when the fragment issue fires            // This is implementing the `OnItemSelectedListener` interface methods            @Override            public            void            onRssItemSelected            (            String            link            )            {            if            (            fragment            !=            null            &&            fragment            .            isInLayout            ())            {            fragment            .            setText            (            link            );            }            }            }                  

in order to proceed the fragment equally re-usable as possible. For more details about this pattern, cheque out our detailed Creating Custom Listeners guide.

Agreement the FragmentManager

The FragmentManager is responsible for all runtime management of fragments including adding, removing, hiding, showing, or otherwise navigating betwixt fragments. As shown above, the fragment manager is also responsible for finding fragments within an activity. Important available methods are outlined below:

Method Description
addOnBackStackChangedListener Add a new listener for changes to the fragment back stack.
beginTransaction() Creates a new transaction to change fragments at runtime.
findFragmentById(int id) Finds a fragment by id normally inflated from activity XML layout.
findFragmentByTag(String tag) Finds a fragment by tag ordinarily for a runtime added fragment.
popBackStack() Remove a fragment from the backstack.
executePendingTransactions() Forces committed transactions to exist applied.

Run into the official documentation for more information. You tin also review the FragmentTransaction to accept a closer look at what modifications can be made at run-time through the managing director.

ActionBar Carte Items and Fragments

One mutual instance is the need for fragment-specific bill of fare items that just evidence upwardly for that fragment. This can be done by adding an onCreateOptionsMenu method to the fragment directly. This works just like the one for the action:

                      @Override            public            void            onCreateOptionsMenu            (            Menu            menu            ,            MenuInflater            inflater            )            {            inflater            .            inflate            (            R            .            bill of fare            .            fragment_menu            ,            card            );            }                  

You and then likewise need to notify the fragment that it's menu items should be loaded within the fragment's onCreate method:

                      @Override            public            void            onCreate            (            Bundle            savedInstanceState            )            {            super            .            onCreate            (            savedInstanceState            );            setHasOptionsMenu            (            true            );            }                  

Clicks tin can exist handled using onClick property every bit usual or more than typically in this case, using the onOptionsItemSelected method in the fragment:

                      @Override            public            boolean            onOptionsItemSelected            (            MenuItem            detail            )            {            // handle item choice            switch            (            particular            .            getItemId            ())            {            case            R            .            id            .            edit_item            :            // do south.thursday.            return            truthful            ;            default            :            return            super            .            onOptionsItemSelected            (            item            );            }            }                  

Notation that the fragment'south method is called just when the Activity didn't consume the event offset. Be sure to check out a more detailed guide near fragments and activity bar if you have more questions.

Navigating Between Fragments

In that location are several methods for navigating between different fragments within a single Action. The primary options are:

  1. TabLayout - Tabs at the height
  2. Fragment Navigation Drawer - Slide out navigation menu
  3. ViewPager - Swiping between fragments

Check the guides linked above for detailed steps for each of these approaches.

Managing Fragment Backstack

A record of all Fragment transactions is kept for each Activity by the FragmentManager. When used properly, this allows the user to hit the device's back button to remove previously added Fragments (non unlike how the back push removes an Action). Simply call addToBackstack on each FragmentTransaction that should exist recorded:

                      // Create the transaction            FragmentTransaction            fts            =            getSupportFragmentManager            ().            beginTransaction            ();            // Supervene upon the content of the container            fts            .            replace            (            R            .            id            .            flContainer            ,            new            FirstFragment            ());            // Append this transaction to the backstack            fts            .            addToBackStack            (            "optional tag"            );            // Commit the changes            fts            .            commit            ();                  

Programmatically, you lot can also pop from the dorsum stack at any fourth dimension through the manager:

                      FragmentManager            fragmentManager            =            getSupportFragmentManager            ();            if            (            fragmentManager            .            getBackStackEntryCount            ()            >            0            )            {            fragmentManager            .            popBackStack            ();            }                  

With this arroyo, we tin easily go on the history of which fragments have appeared dynamically on screen and let the user to easily navigate to previous fragments.

Fragment Hiding vs Replace

In many of the examples above, we call transaction.replace(...) to load a dynamic fragment which beginning removes the existing fragment from the action invoking onStop and onDestroy for that fragment before adding the new fragment to the container. This can be adept because this will release memory and brand the UI snappier. However, in many cases, nosotros may want to keep both fragments around in the container and merely toggle their visibility. This allows all fragments to maintain their land because they are never removed from the container. To do this, we might modify this lawmaking:

                      // Inside an action            private            FragmentA            fragmentA            ;            private            FragmentB            fragmentB            ;            private            FragmentC            fragmentC            ;            @Override            protected            void            onCreate            (            Bundle            savedInstanceState            )            {            super            .            onCreate            (            savedInstanceState            );            setContentView            (            R            .            layout            .            activity_main            );            if            (            savedInstanceState            ==            null            )            {            fragmentA            =            FragmentA            .            newInstance            (            "foo"            );            fragmentB            =            FragmentB            .            newInstance            (            "bar"            );            fragmentC            =            FragmentC            .            newInstance            (            "baz"            );            }            }            protected            void            displayFragmentA            ()            {            FragmentTransaction            ft            =            getSupportFragmentManager            ().            beginTransaction            ();            // removes the existing fragment calling onDestroy            ft            .            replace            (            R            .            id            .            flContainer            ,            fragmentA            );            ft            .            commit            ();            }                  

to this approach instead leveraging add, evidence, and hide in the FragmentTransaction:

                      // ...onCreate stays the same            // Replace the switch method            protected            void            displayFragmentA            ()            {            FragmentTransaction            ft            =            getSupportFragmentManager            ().            beginTransaction            ();            if            (            fragmentA            .            isAdded            ())            {            // if the fragment is already in container            ft            .            evidence            (            fragmentA            );            }            else            {            // fragment needs to exist added to frame container            ft            .            add            (            R            .            id            .            flContainer            ,            fragmentA            ,            "A"            );            }            // Hide fragment B            if            (            fragmentB            .            isAdded            ())            {            ft            .            hide            (            fragmentB            );            }            // Hibernate fragment C            if            (            fragmentC            .            isAdded            ())            {            ft            .            hide            (            fragmentC            );            }            // Commit changes            ft            .            commit            ();            }                  

Using this approach, all 3 fragments will remain in the container once added initially so we are only revealing the desired fragment and hiding the others within the container. Bank check out this stackoverflow for a discussion on deciding when to replace vs hide and evidence.

Nesting Fragments within Fragments

Inevitably in sure cases you volition want to embed a fragment within another fragment. Since Android four.2, you take the ability to embed a fragment inside some other fragment. This nested fragment is known as a child fragment. A common situation where you might want to nest fragments is when yous are using a sliding drawer for elevation-level navigation and one of the fragments needs to brandish tabs.

Note that one limitation is that nested (or child) fragments must be dynamically added at runtime to their parent fragment and cannot be statically added using the <fragment> tag. To nest a fragment in another fragment, get-go we need a <FrameLayout> or alternatively a ViewPager to contain the dynamic kid fragment in the res/layout/fragment_parent.xml layout:

                      <?xml version="ane.0" encoding="utf-eight"?>            <LinearLayout            xmlns:android=            "http://schemas.android.com/apk/res/android"            android:layout_width=            "match_parent"            android:layout_height=            "match_parent"            android:orientation=            "vertical"            >            <TextView            android:layout_width=            "wrap_content"            android:layout_height=            "wrap_content"            android:text=            "I am the parent fragment"            />            <FrameLayout            android:id=            "@+id/child_fragment_container"            android:layout_width=            "match_parent"            android:layout_height=            "wrap_content"            />            </LinearLayout>                  

Notice that there'southward a FrameLayout with the id of @+id/child_fragment_container in which the child fragment will exist inserted. Inflation of the ParentFragment view is within the onCreateView method, just as was outlined in earlier sections. In add-on, we would also define a ChildFragment that would accept its own distinct layout file:

                      // Peak-level fragment that volition contain the child            public            class            ParentFragment            extends            Fragment            {            @Override            public            View            onCreateView            (            LayoutInflater            inflater            ,            ViewGroup            container            ,            Packet            savedInstanceState            )            {            return            inflater            .            inflate            (            R            .            layout            .            fragment_parent            ,            container            ,            false            );            }            }            // Kid fragment that will be dynamically embedded in the parent            public            class            ChildFragment            extends            Fragment            {            @Override            public            View            onCreateView            (            LayoutInflater            inflater            ,            ViewGroup            container            ,            Package            savedInstanceState            )            {            // Demand to define the child fragment layout            return            inflater            .            inflate            (            R            .            layout            .            fragment_child            ,            container            ,            simulated            );            }            }                  

At present we can add the child fragment to the parent at runtime using the getChildFragmentManager method:

                      // Tiptop-level fragment that will comprise the child            public            class            ParentFragment            extends            Fragment            {            @Override            public            View            onCreateView            (            LayoutInflater            inflater            ,            ViewGroup            container            ,            Package            savedInstanceState            )            {            render            inflater            .            inflate            (            R            .            layout            .            fragment_parent            ,            container            ,            false            );            }            // This event is triggered soon afterward onCreateView().            // onViewCreated() is only called if the view returned from onCreateView() is non-null.            // Whatsoever view setup should occur hither.  E.yard., view lookups and attaching view listeners.            @Override            public            void            onViewCreated            (            View            view            ,            Parcel            savedInstanceState            )            {            insertNestedFragment            ();            }            // Embeds the kid fragment dynamically            private            void            insertNestedFragment            ()            {            Fragment            childFragment            =            new            ChildFragment            ();            FragmentTransaction            transaction            =            getChildFragmentManager            ().            beginTransaction            ();            transaction            .            supercede            (            R            .            id            .            child_fragment_container            ,            childFragment            ).            commit            ();            }            }                  

Note that yous must e'er use getChildFragmentManager when interacting with nested fragments instead of using getSupportFragmentManager. Read this stackoverflow mail for an explanation of the difference between the two.

In the child fragment, we can use getParentFragment() to get the reference to the parent fragment, similar to a fragment'southward getActivity() method that gives reference to the parent Activity. See the docs for more information.

Managing Configuration Changes

When yous are working with fragment every bit with activities, you need to make sure to handle configuration changes such as screen rotation or the activity being closed. Exist sure to review the configuration changes guide for more details on how to save and restore fragment state.

References

  • http://programmer.android.com/reference/android/app/Fragment.html
  • http://developer.android.com/training/basics/fragments/creating.html
  • http://programmer.android.com/guide/components/fragments.html
  • http://www.vogella.com/articles/AndroidFragments/article.html
  • http://xperiment-andro.blogspot.com/2013/02/nested-fragments.html

Source: https://guides.codepath.com/android/creating-and-using-fragments

Posted by: byrdbourponshave.blogspot.com

0 Response to "How To Update Initial Activity Page After Updating The Adapter"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel