Sun. Nov 28th, 2021
Fragments and Action Bars –
Fragments and Action Bars –

<br /> assist<br />

The Android framework comprises quite a lot of UI parts that permit a typical really feel to design easy UIs — one is the ActionBar. These UI parts combine fragments that are related to a view. Fragments allow us to construct reusable and extensible UIs.

What this lecture will train you

  • How to construct the Action Bar app, which makes use of tabs, pages and fragments
  • Creating the app with tabs and content material for pages
  • Setting up Menus
  • Fragments, Fragment lifecycle and fragment layouts

Resources

Checkout the demo undertaking

  • Download the demo the actiontabs.zip app particularly designed to go together with these notes.

ActionTab app

ActionTab is a straightforward software used to display the use on the App Bar and fragments. If you click on by means of the tabs you’ll discover to reply to the query – why Dartmouth.

Fragments are related to the UI. We will develop the ActionTab app to finest illustrate how fragments can use Android UI parts corresponding to App Bar (extra on that in a second). The ActionTab app will mix a number of fragments (4 in all) in a single exercise to construct a multi-pane UI. These fragments might be thought of self-contained parts and might be reused by a number of actions doubtlessly throughout a number of functions.

The app is made up of 4 tabs and 4 corresponding fragments.

Note, that when the app is proven in panorama the App Bar is configured in a different way from the traditional portrait view — Android rearranges the icons seen within the motion app/bar; that’s, in panorama the “add” possibility is proven as an icon on the actionbar relatively than within the drop down, as is the case in portrait mode; we present the panorama beneath:

Play with the app to get a really feel for the UI — cool hey? Simple, compact and a pleasant approach to construct up the options and providers provided by your app. We will use this App Bar and fragment mixture as a part of Lab2.

There is one exercise and 4 fragments on this undertaking:

  • exercise: MajorActivity.java
  • fragments: ChatFragment.java, DiscoverFragment.java, MeetFragment.java, Get togetherFragment.java
  • layouts: every exercise and fragment has a format
  • menu: that is new the motion bar has a menu that’s in res/menu/important.xml

The programs design diagram (beneath) captures the principle parts and their interplay. This isn’t meant to be an in depth diagram. Rather, it exhibits the principle exercise, the 4 fragments and their layouts. The menu and manifest are additionally proven.

Action App/Bar

Action App (observe Action Bar and Action App are the sameish however Action Bar is depreciated — thanks Google) is a straightforward UI part that can be utilized by many alternative functions — it provides a typical really feel that may be personalized to the particular wants on completely different functions. Let’s take a better take a look at the motion bar of our app — now proven in portrait mode, as proven beneath. The motion bar exhibits the applying icon on the left — the CS emblem, adopted by the exercise title — ActionTab. Our exercise defines quite a lot of “action items” (in menu/important.xml). Selected objects might be made seen on the motion bar corresponding to search and ship (that are instantly accessible as icons outlined within the menu/important.xml). If a menu merchandise doesn’t seem as an motion merchandise (for instance add, share, suggestions) then the motion bar locations it within the overflow menu — the motion merchandise icons and the overflow menu are down within the determine(left). The overflow menu button is proven on far proper of the determine — 3 dots stacked. If we click on on that we see the hidden menu choices — proven within the determine (proper).

Tabs

Tabs within the motion bar are sometimes the place you set titles for various pages in your app. They make it straightforward to discover and swap between completely different views or useful elements of your app, or to browse categorized knowledge units. Check out the Google Play app in your cellphone for a fast demonstration of scrollable tabs, the place tab strip indicators transfer easily from tab to tab. Users can acquire steady contact suggestions as they swipe between pages.

Developing sliding tabs with TabLayout and ViewPager

Add TabLayout and ViewPager to the principle.xml file. At onCreate(), the MajorActivity will load these two parts to render the sliding tabs and swipeable pages. To use the ViewPager class, that you must import AndroidX library to your undertaking. Check a earlier put up on import the library in Android Studio


viewpager.widget.ViewPager
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/viewpager"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">

    google.android.materials.tabs.TabLayout
    android:id="@+id/tab"
    android:layout_width="match_parent"
    android:layout_height="wrap_content" />

viewpager.widget.ViewPager>

Creating the App Bar and Tabs

Our design makes use of ViewPager to modify between Fragment objects, and every Fragment is titled by one sliding tab, as proven within the code snippet. ViewPager is most frequently used along side Fragment, which is a handy approach to provide and handle the lifecycle of every web page. There are normal adapters carried out for utilizing fragments with the ViewPager, which cowl the commonest use circumstances. These are FragmentPagerAdapter and FragmentStatePagerAdapter; every of those lessons have easy code displaying construct a full person interface with them. In Android, adapters are a bridge between Adapter View (e.g., ViewPager, ListingView, and so forth.) and the underlying knowledge sources for that view (e.g., arraylists, databases, fragments, and so forth.). We will revisit the idea of adapter within the week 4.



public class MajorActivity extends AppCompatActivity {

/** Called when the exercise is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
           tremendous.onCreate(savedInstanceState);
       setContentView(R.format.important);

       // Define TabLayout (proven at prime)
       // and ViewPager (proven at backside) within the format.
       // Get their situations.
       tabLayout = discoverViewById(R.id.tab);
       viewPager = discoverViewById(R.id.viewpager);

           // create a fraction record so as.
       fragments = new ArrayList();
       fragments.add(new DiscoverFragment());
       fragments.add(new ChatFragment());
       fragments.add(new MeetFragment());
       fragments.add(new Get togetherFragment());

           // use FragmentPagerAdapter to bind the TabLayout
       // (tabs with completely different titles) and ViewPager (completely different pages
       // of fragment) collectively.
       myViewPagerAdapter = new ActionTabsViewPagerAdapter(
                  this.getSupportFragmentSupervisor(),
                  fragments);
       viewPager.setAdapter(myViewPagerAdapter);
       tabLayout.setupWithViewPager(viewPager);
       tabLayout.setTabMode(TabLayout.MODE_FIXED);

}

 

Once the tabs are arrange we create 4 new fragments; we merely use the brand new key phrase in entrance of the category names for every of the fragments created within the information:

  • ChatFragment.java
  • DiscoverFragment.java
  • MeetFragment.java
  • Get togetherFragment.java

These are all just about equivalent code. Each fragment inflates its personal format (e.g., R.format.chatfragment) in onCreateView().

Next, in our personalized ActionTabsViewPagerAdapter we arrange the titles for every of the created tabs.

    public CharSequence getPageTitle(int place) {
        swap (place) {
            case CHAT:
                return UI_TAB_CHAT;
            case FIND:
                return UI_TAB_FIND;
            case MEET:
                return UI_TAB_MEET;
            case PARTY:
                return UI_TAB_PARTY;
            default:
                break;
        }
        return null;
    }

The menu declares the entire menu objects. We present just a few objects beneath. The object ID is ready up; observe Android has quite a lot of good icons we are able to use and within the case beneath we use the search and ship icons from @android:drawable; regards “ifRoom”: You can specify {that a} menu merchandise seem as an motion merchandise within the XML file through the use of android:presentAsAction="ifRoom" as proven above in our menu for every of the ingredient. Depending on area (might be a pill or cellphone, or might be a cellphone flipping between portrait and panorama) the merchandise could be within the actionbar or if there is no such thing as a room it would seem within the overflow menu. The closing of the merchandise arrange is a title @string/ui_menu_send that can be utilized within the overflow menu if it might probably’t be accommodated within the motion bar.

"1.0" encoding="utf-8"?>
"http://schemas.android.com/apk/res/android" >
 
    "@+id/menuitem_search"
        android:icon="@android:drawable/ic_menu_search"
        android:presentAsAction="ifRoom"
        android:title="@string/ui_menu_search">
    
    "@+id/menuitem_send"
        android:icon="@android:drawable/ic_menu_send"
        android:presentAsAction="ifRoom"
        android:title="@string/ui_menu_send">
    
 
    **snippet**

The onCreateOptionsMenu() callback is invoked when the exercise is created to inflate the principle.xml within the menu folder as mentioned above — this inflates the XML menu sources that populates the he motion bar and overflow menu. You can add menu objects to the menu programmatically utilizing onCreateOptionsMenu() however in our instance we merely inflate the objects arrange in important.xml.

            @Override
            public boolean onCreateOptionsMenu(Menu menu) {
                        MenuInflater inflater = getMenuInflater();
                        inflater.inflate(R.menu.important, menu);
                        return true;
            }

If you added the menu merchandise from a fraction, through the Fragment class’s onCreateOptionsMenu callback, then the system calls the respective onOptionsItemSelected() technique for that fragment when the person selects one of many fragment’s objects. When any of the choices are chosen by the person the onOptionsItemSelected is known as with the reference to the associated MenuItem. In most circumstances the callback justs shows toast however within the case of stop we name end() to shut the app.

            @Override
            public boolean onOptionsItemSelected(MenuItem merchandise) {
                        swap (merchandise.getItemId()) {
                        case R.id.menuitem_search:
                                    Toast.makeText(this, getString(R.string.ui_menu_search),
                                                            Toast.LENGTH_LONG).present();
                                    return true;
                        case R.id.menuitem_send:
                                    Toast.makeText(this, getString(R.string.ui_menu_send),
                                                            Toast.LENGTH_LONG).present();
 
                        ** snippet**
 
                        case R.id.menuitem_quit:
                                    Toast.makeText(this, getString(R.string.ui_menu_quit),
                                                            Toast.LENGTH_SHORT).present();
                                    end(); // shut the exercise
                                    return true;
                        }
                        return false;
            }
 

Fragments

Up till now we now have used actions as drivers to show views to the display. The earlier instance every display is related to an exercise that’s used to render and handle the person interplay with the view. All that modifications on this lecture. We transfer away from actions and begin to use fragments — a fraction is now used to render and supervisor a selected UI view. Think of fragments as light-weight actions for now. Your software nonetheless wants actions however we do not use them to solely render views. Most functions, and ones we’ll develop, embrace a number of exercise and fragments.

What are fragments?

  • Fragments are elements of software’s UI or habits which are built-in into actions — a fraction wants an exercise to run.
  • Fragments are versatile and reusable parts outlined by the programmer
  • every fragment has its personal lifecycle and related UI (for instance, a fraction for the person to enter profile info, one other one to render maps).
  • Fragments current a constant UI throughout completely different apps and units; fragments are versatile in adapting the person expertise throughout these completely different environments.

In implementation there are appreciable variations; for instance, an exercise must be specified within the manifest, whereas fragments don’t as a result of they’ll solely exist within the context of an exercise and are coupled to the exercise state. While fragments are strongly built-in into the UI you should use fragments with no view or UI parts. Fragments can implement quite a lot of software behaviors, corresponding to, code to deal with listeners, information, database, and so forth. These varieties of fragments might be considered invisible employee for the exercise — extra in a while this. For now we’ll simply think about fragments when utilized to the UI.

Why use fragments over actions?

A fraction is a modular a part of an exercise. It has its personal lifecycle and receives its personal enter occasions. Fragments can created, added or eliminated whereas the exercise is operating. Consider a fraction a “sub activity” which you can reuse in several actions. But you would ignore fragments and simply use actions if you want — however not suggest. Why use fragments over actions? Well fragments are wired to create reusable Android person inferences parts — nevertheless, it’s true to say you’ll be able to implement related software UIs with a pure exercise answer, which could be complicated for college students. Here are some the explanation why it is best to use fragments as a designer:

  • Consider the diagram beneath. You are designing a cool new app that you really want gazillions of individuals to make use of on all kinds of telephones and tablets with completely different sized screens. The determine exhibits how your UI based mostly on fragment design may run on a pill and cellphone UI; within the case of the pill with bigger display actual property the UI fragment parts are rendered facet by facet however on the cellphone with a smaller kind issue the 2 fragments are handled in a different way and introduced into focus at completely different instances. The exercise that handles the UI is wise sufficient to adapt the UI to the kind of gadget.
  • As we’ll see within the pattern undertaking code ActionTab fragments have been built-in into UI parts corresponding to App Bar which is a the suggest approach to construct a typical UI really feel throughout completely different apps. We will talk about App Bar later in these notes the place we bind tabs (to navigate your app) on the App Bar to fragments. When we take a look at the callback (i.e., ActionBar.TabListener interface) for dealing with the occasion when the person faucets a tab the interface passes a FragmentTransaction as an enter argument to the onTabSelected technique. In transient, many UI parts assume you’re utilizing fragments and not actions — because of this, fragments are wired into the UI and actions aren’t.

Fragment and actions akin to processes and threads

Fragments are reusable UI however may also be thought of light-weight in how they deal with operations on the UI. As I discussed earlier than you are able to do most issues with actions that fragments do however think about for the second (in case you did this) the connection between design utilizing all processes or threaded design. Fragments might be thought of to be threads in such a selection, as proven beneath.

Fragment Lifecycle

Though Fragment defines its personal lifecycle, that lifecycle depends on its exercise: if the exercise is stopped, no fragments within it may be began; when the exercise is destroyed, all fragments will likely be destroyed.

A fraction runs with within the exercise and the exercise lifecycle that we mentioned. So it an exercise is stopped so are all its fragments. Similarly if the exercise is destroyed so are all of the related fragments. However, when an exercise is operating (i.e., onResume() state) fragments might be independently managed — added, changed or eliminated. As we’ll see what we talk about the ActionTab software we’ll use fragment transactions to take away and change fragments related to the motion bar tabs: corresponding to:

  • ft.take away(fragment); take away a fraction from the UI
  • ft.change(R.id.fragment_container, fragment); change one fragment (or view) with one other.

These fragment transactions permit the exercise to handle the again stack – a again stack entry within the exercise is a document of the fragment transaction that occurred. This, for instance, permits the person to reverse a fraction transaction (navigate backwards), by urgent the again button.

The fragment lifecycle diagram proven beneath seems sophisticated however as we talk about it think about that this set of fragment states run within the operating state of the exercise lifecycle diagram we mentioned in earlier lecture on exercise lifecycle. Therefore the state diagram proven beneath is just legitimate when the exercise related to the fragment

Like the exercise lifecycle the fragment lifecycle is represented by a bunch of states and related occasion handlers, that are triggered when a fraction is:

  • created
  • resumed
  • paused
  • stopped
  • destroyed

In addition there are a selection of callbacks related to quite a lot of fragment particular occasions, corresponding to, 1) binding and unbinding a fraction from its exercise; 2) when a fraction is created and destroyed. If you take a look at the core states proven within the determine you see:

  • fragment is added
  • fragment is lively
  • fragment is destroyed

Fragment lifecycle occasions

Many occasions can happen between these states — for instance the person can hit the again button.

  • onAttach() is known as when the Fragment is hooked up to its guardian exercise
  • onCreate() is known as to initially create the fragment
  • onCreateView() is known as to created its person interface — it inflates the fragment UI
  • onActivityCreated() is known as as soon as the guardian exercise and the fragment UI are created.
  • onStart() is known as the beginning of the seen lifetime, any UI modifications might be utilized earlier than the fragment goes seen
  • onResume() is known as at first of the lively lifetime corresponding to resuming any paused UI updates wanted by the fragment that have been suspended when it turned inactive.
  • onPause() referred to as on the finish of the lively lifetime; persist all edits or state modifications, droop UI updates, threads, or CPU intensive processes that do not have to be up to date when the Activity is not the lively foreground exercise
  • onSaveInstanceState() referred to as to save lots of UI state modifications on the finish of the lively lifecycle
  • void onStop() referred to as on the finish of the seen lifetime
  • onDestroyView() referred to as when the fragment’s view is indifferent
  • onDestroy() referred to as on the finish of the total lifetime
  • onDetach() referred to as when the Fragment has been indifferent from its guardian exercise.

If we think about the ActionTab app it has 4 fragments – one for every tab view. As the use faucets by means of the tab choices the fragment transitions by means of the states within the lifecycle diagram — shifting say from being in focus in onResume() to hidden in onPause(). But the entire fragment lifecycle is tightly coupled to the exercise but additionally ruled by the person interplay with the UI (as is the case with the ActionTab app). The exercise can dynamically assemble the UI and its related fragments — corresponding to including and eradicating fragments the place every fragment transitions by means of its full, seen and lively lifecycle a number of instances throughout the lifetime of its guardian exercise — for instance as a fraction is added and faraway from the view.

See MySkeletonFragment.java for an instance of a skeleton fragment. There are many occasions and we’ll solely use just a few of those occasions when it comes to populating code. So do not be overwhelmed — at the very least, not but ;-). Let’s talk about among the essential occasions.

onAttach() and onDetach() occasions

The lifecycle begins and ends when a fraction is hooked up and indifferent from its guardian exercise. The onAttach() occasion happens earlier than the fragment’s UI is created and earlier than the fragment or its guardian exercise have accomplished initialization. Keep this in thoughts once we are trying on the ActionTab exercise’s onCreate() when it creates its fragments. It is a good suggestion to create fragments within the actions onCreate() to make sure they’re created solely as soon as within the fragment lifetime.

onCreateView() occasion

The fragment’s UI is created and destroyed in onCreateView() and onDestroyView() callbacks, respectively. The onCreateView() technique initializes the fragment by inflating the UI, getting references and binding any knowledge to the views that it comprises — and then any addition initialization corresponding to establishing providers (we’ll discuss providers in a while within the course).

onCreateView(): ActionTab instance

The onCreateView()’s important job in code we’ll write is a one liner — taken from DiscoverFragment.java within the ActionTab app:

return inflater.inflate(R.format.findfragment, container, false)

An instance of a fraction format

The R.format.findfragment is the ID for an XML format useful resource to load (e.g., R.format.findfragment). This is outlined within the res/format/findfragment.xml of the ActionTab undertaking. This specifies the UI for the fragment, which is only a easy picture however might be a complicated view group.

"1.0" encoding="utf-8"?>
"http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >
 
    "@+id/imageViewOfGirl"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:contentDescription="@string/ui_love_picture"
        android:orientation="horizontal"
        android:src="@drawable/ic_eye" />
 

Creating fragments and inflating: MeetFragment.java instance

A fraction extends the Fragment class as proven beneath. When the MajorActivity creates the fragments it calls onCreateView() for all fragments. All onCreateView() creates and returns the view hierarchy related to the fragment– basically it returns the view for the fragment’s UI. The code beneath overrides the onCreateView() handler into inflate and return the requires view hierarchy; that’s, R.format.meetfragment, as proven beneath. Note, in case your fragment doesn’t use a UI (corresponding to offering the exercise with background habits) you don’t inflate in fact.

Importantly, fragments would not have to be registered within the manifest like actions are. And, because the fragment lifecycle, fragments are tied to the state of the exercise so this makes good sense; that’s, they cannot exist with out an exercise.

public class MeetFragment extends Fragment {
            
    @Override
    public View onCreateView(FormatInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        // Inflate the format for this fragment
        return inflater.inflate(R.format.meetfragment, container, false);
    }
    
}

By admin