Langsung ke konten utama

What is Fragment

The concept of a fragment is tied very tight with the concept of an activity. And if you don't understand clearly what activity is I encourage you to read last week's post first and then return to fragments.

Also, here's the post that will help you to get a nice overview of basic Android classes such as Context, Activity, Fragment, Thread etc.

What is the problem

With the growth of popularity of Android system more and more developers started to pay attention to it. More and more apps were developed for Android and it entailed more and more complexity in these apps. In particular, this complexity was growing in activities and layouts.

Possible solutions

First of all, developers wanted something that would be reusable in several activities. And this, as I think, gave a birth to ActivityGroup

As the documentation says it's
A screen that contains and runs multiple embedded activities
which seems like a bit overhead. In this implementation, every activity has its' own context, while developers wanted something that would be a part of one single activity context.

And with the arrival of tablets, this problem became more obvious. And at that moment of time Google introduced the fragment concept. Intentionally, fragments were designed to meet exactly the needs of tablet layouts, but now there are a plethora of use-cases for fragments. 

So what is Fragment

Fragment represents a behavior or part of the user interface in an activity. Multiple fragments can be used in one activity to represent different parts of the activity. Also, one fragment can be used in different activities.

A fragment itself doesn't know about other fragments in the activity part of which it appears to be.
By definition, it's independent part of an activity and can do its' job even without other fragments. So if you fall into a situation when one of your fragments depends on another fragment you should think about the design of your application.

A fragment always should be embedded in an activity and the activity's lifecycle actually defines the fragment's lifecycle. If an activity is on pause then all of its' fragments are on pause. If an activity is destroyed then all of its' fragments are destroyed. If an activity is running not all (if at all) of its' fragments are running, though.

While activity is running, a developer can manually and independently control the fragment's lifecycle. For example, he/she can add new fragment, or delete old one or pause it. 

Also, while doing these transactions it's possible to add them in the backstack so the user can revert a transaction by pressing "back" button.

And it worth to mention that fragments operate on the same level of abstraction as activities.

There are two types of fragments: static and dynamic.

Static fragments

Generally, static fragments are fragments that will not be replaced by other fragments during the lifecycle of an activity. To add an instance of this fragment to your activity you can use the <fragment> tag in the XML file that represents your activity's layout. And that's it your fragment will work as if it would be an activity. Also, using this approach you will be able to find this fragment using its' android:id.

Dynamic fragments

I think that the name is self-explanatory. Yeah, right, dynamic fragments are the ones that could be added, deleted and replaced while corresponding activity is running. These fragments are added in ViewGroup programmatically using FragmentManager. To refer to this type of fragments during runtime you would use a special tag that should be unique for every fragment in the activity.

A couple of use cases

The most popular and easiest use-case for fragments is the implementation of master-detail flow on tablets.

Master-detail flow is the technique that used in many mobile apps. Generally, it's when you have a list of items that describe something briefly and the screen that shows details of this something. For example, in an email app, you don't see a full email right away you see the title, maybe some text but you should tap on it to see details.



Usually, on smartphones, there is no place for both, master and detail layouts and these are separate activities. But tablets are much much bigger than smartphones so it's more convenient to have everything on one screen. Like in this picture.


So in this case, fragments perform like both: part of an activity and reusable parts. You can use detail fragment in smartphone and tablet layouts, but in smartphone layout, it will have

Also, fragments can be used without layout as a separate thread of your activity, but when do so remember that the fragment's lifecycle depends on the activity's lifecycle.

Wrap up

Fragments are powerful, as said with great power comes great responsibility and, in software development, complexity. But you don't need to understand all this complex underlying basements of fragment to take advantage of them.

For me, fragments were something that only sophisticates the structure of an application. But it was because the lack of understanding. Now I understand what is fragment and think that it's elegant solution to the problem that arose with the growth of Android system. 

And I hope that I tackled this lack of understanding for you. If I didn't and you still have questions fell free to ask in comment section below!

That's all for today, see you in the next one!

P.S. If you want to bee up to date about posts on this blog follow me on Twitter.

Komentar

Postingan populer dari blog ini

Android Tutorial: Use LeakCanary to detect memory leaks

Overview The memory leak can be a headache to detect and to resolve, small memory leaks can be hidden and may be seen after a long usage of the application and hunting memory leaks is not a simple task. In this tutorial we will create a leaked application and we will use the LeakCanary library to detect the memory leak. Step 1: add the LeakCanary dependency to the application Modify the app/build.gradle to add the LeakCanary dependency as follows: Step 2: Extend and configure the Application class We need to call LeakCanary.install in onCreate method: Step 3: Create a leaked activity For this we will create a singleton class that saves the context: Then, the main activity (leaked one), will use the singleton and then we'll go to a new activity: Then, in the new activity we'll call System.gc to force the garbage collector in order to accelerate the analysis. Step 4: Retrieve the analysis result A nice notification can be shown: The result can be retrieved from logcat: Source c...

QR-Code Generator - Library

In this Post, I introduce my new Gradle Library. This Library is used to Generate QR Code Automatically for our specified input. How to Import the Library: Gradle: compile 'androidmads.library.qrgenearator:QRGenearator:1.0.0' Permission: <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/> How to use this Library: After importing this library, use the following lines to use this library. The following lines are used to generated the QR Code // Initializing the QR Encoder with your value to be encoded, type you required and Dimension QRGEncoder qrgEncoder = new QRGEncoder(inputValue, null, QRGContents.Type.TEXT, smallerDimension); try { // Getting QR-Code as Bitmap bitmap = qrgEncoder.encodeAsBitmap(); // Setting Bitmap to ImageView qrImage.setImageBitmap(bitmap); } catch (WriterException e) { Log.v(TAG, e.toString()); } Save QR Code as Image // Save with location, value, bitmap returned and type of Image(JPG/PNG). QRGSaver.save(s...

FlatBuffers Android Tutorial

FlatBuffers is an efficient cross platform serialization library for C++, Java, C#, Go, Python and JavaScript. It was originally created at Google for game development and other performance-critical applications. FlatBuffers is Open Source (Apache license V2) and available on GitHub . It's currently used by:   Cocos2d-x , the open source mobile game engine and used to serialize the game data. Facebook uses it for client-server communication in the Android app (see the article) . Fun Propulsion Labs at Google in most of libraries and games. Solution overview  The schema will be defind in JSON format, then it will be converted to FlatBuffer format outside the application The Java classes of the Data model will be generated manually using flatc (FlatBuffer compiler) Step 1: Build FlatBuffers Download the source code in Google’s flatbuffers repository .  The build process is described on Google's documentation FlatBuffers Building .  On MacOS for example: Open the ...