How To Create a Fragment Activity For Android Apps - Hive Programmers

avatar

Greetings to everyone and welcome to my favorite science community online, StemSocial.

It's @skyehi, and I'm super excited to be back in this community. I've been away for only a day, and I've already missed sharing my blogs.

Polish_20240128_185638729.pngOriginal Image Source by 200degrees from Pixabay

YpihifdXP4WNbGMdjw7e3DuhJWBvCw4SfuLZsrnJYHEpsqZFkiGGNCQTayu6EytKdg7zA3LL2PbZxrJGpWk6ZoZvBcJrADNFmaFEHagho8WsASbAA8jrpnELSvRtvjVuMiU1C5ADFX1vJgcpDvNtue9Pq83tjBKX62dqT5UoxtDk.png

We'll continue the series on Android App Development Tutorials by looking at Fragment activities in this episode.

In Android development, Fragments or fragment activities are very crucial components that allow app developers to create modular and reusable user interfaces.

In other words, fragments allow developers to integrate a lot of activities in a single page.

Fragment activities are what make multiple tabs possible in apps. You could have Android apps that show bottom navigation or slider navigation with different activities or pages in them.

Each activity, instead of being a regular activity, would have to be a fragment activity.

Fragments are more like independent components that can be reused across multiple activities.

In today's episode, I felt the real need to introduce my readers and followers to fragments in Android App development, since in the subsequent episode during the advanced part of the series, we'll be utilizing fragment activities a lot.

I hope you're ready for this tutorial, guys. Let's get started with today's work, shall we?

Prerequisites

For the benefit of newcomers to Android App development or my series, I'll share with you the required software you need to be able to go through with this tutorial.

  • Android Studio IDE - the platform on which we'll develop this and all other Android apps.

  • Java Development Kit, JDK - You need to install JDK correctly on your PC for your PC to be able to execute Java commands or codes.

  • Physical Android Device or Emulator - After building the app, we'll need to test it either on an emulator or a physical Android device.

If you have all these checked out, you're absolutely ready to go through with this tutorial.

2dk2RRM2dZ8gKjXsrozapsD83FxL3Xbyyi5LFttAhrXxr16mCe4arfLHNDdHCBmaJroMz2VbLrf6Rxy9uPQm7Ts7EnXL4nPiXSE5vJWSfR53VcqDUrQD87CZSpt2RKZcmrYrze8KanjkfyS8XmMCcz4p33NZmfHE4S9oRo3wU2.png

Creating a New Project

We're going to create a whole new project in Android Studio and create a fragment activity in it.

Start by opening the Android Studio IDE and clicking on "Create A New Android Studio Project".

To keep things as simple as possible, we'll go with a basic "Empty Activity" as the template for our project.

So choose empty activity as the project template and click on the "Next" button.

When Android Studio loads your new project, it will give you a default MainActivity.java file and an activity_main.xml file.

The java file is where your backend code or logic of the app will be written, and the xml file is where the frontend code or user interface design code will be written.

However, we will be creating a whole new Java and XML file as a fragment activity.

That was just by the way, guys. Let's continue with creating our new Android Studio project.

After you select your desired template and click the next button, you can set both the package name and app name of your app project.

Also, for the purpose of this particular tutorial, ensure that Java is selected as the programming language of your project and not Kotlin.

When you're satisfied with the project configuration, click the "Finish" button and wait while Android Studio loads your new project space.

Creating Fragments

Now, guys, there's a really simple and easy way to create fragment activities in the Android Studio IDE or software.

  • The steps are pretty easy.

Start by right-clicking on the app folder, usually at the top left side bar of your Android Studio IDE, and locate the New button.

Click on the fragment button, and it should take a couple of seconds to load your new fragment pages.

For this tutorial, we'll be creating two fragments so you can familiarize yourself with creating multiple fragments.

So, guys, I'll create two fragments and name them FragmentA and FragmentB.

Here's a simplified instruction to create a new fragment in Android Studio

Right-click on the app folder, navigate to New -> Fragment -> Fragment (Blank), and create two fragments: FragmentA and FragmentB.

YpihifdXP4WNbGMdjw7e3DuhJWBvCw4SfuLZsrnJYHEpsqZFkiGGNCQTayu6EytKdg7zA3LL2PbZxrJGpWk6ZoZvBcJrADNFmaFEHagho8WsASbAA8jrpnELSvRtvjVuMiU1C5ADFX1vJgcpDvNtue9Pq83tjBKX62dqT5UoxtDk.png

Design Fragment Layouts

Now, guys, since each fragment page would require a frontend user interface and a backend logic depending on what activity or task will be done on that particular fragment, we need to design layouts for both.

I may not be creating any particular user interface, so you can design the UI for each fragment yourself, according to your requirements.

To do that, since we've already created two fragments, open the fragment_a.xml and fragment_b.xml layout files and add your layout designs.

Implement Fragment Classes

We're through with the frontend, and it's time to work on the backend codes.

To work on the logic code, like I mentioned earlier, we need to create Java classes for FragmentA and FragmentB and implement the necessary logic.

When I say necessary logic, I mean two things; first is the logic code that would identify the activity as a Fragment activity and also the logic of whatever task that fragment page will execute.

Here's how your FragmentA java code should look like. This should be done for FragmentB as well, guys.

public class FragmentA extends Fragment {
    public FragmentA() {
        // Required empty public constructor
    }

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

YpihifdXP4WNbGMdjw7e3DuhJWBvCw4SfuLZsrnJYHEpsqZFkiGGNCQTayu6EytKdg7zA3LL2PbZxrJGpWk6ZoZvBcJrADNFmaFEHagho8WsASbAA8jrpnELSvRtvjVuMiU1C5ADFX1vJgcpDvNtue9Pq83tjBKX62dqT5UoxtDk.png

Implementing FragmentActivity

Now, guys, since our main activity will be hosting these fragments, we need to modify it to host them.

Of course, you can create any full activity in your app to host the fragments, however, to keep things simplified since it's a beginner's tutorial, I'll let the Main activity host the two fragments.

We would have to modify the main activity for it to be able to host these fragments.

So, guys, inside your main activity's layout file, which would be the activity_main.xml file, add a FrameLayout element that would act as the container for the two fragments we created.

Here's how the layout code would look like

Remember, guys, this is going to be done inside your activity_main.xml file.

<FrameLayout
    android:id="@+id/fragmentContainer"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_marginTop="?android:attr/actionBarSize"/>

We've worked on the layout of the activity that would host the fragments, and it's now time to work on the java file of the activity that would host the fragments.

So head over to your MainActivity.java and use a FragmentManager class to dynamically add the fragments to the container.

Depending on the number of fragments you wish to add, we will include all inside the loadFragment method.

I only added Fragment A so you can add Fragment B as well, guys.

Here's how the code should look like

public class MainActivity extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // Load FragmentA by default
        loadFragment(new FragmentA());
    }

    private void loadFragment(Fragment fragment) {
        FragmentManager fragmentManager = getSupportFragmentManager();
        FragmentTransaction transaction = fragmentManager.beginTransaction();
        transaction.replace(R.id.fragmentContainer, fragment);
        transaction.addToBackStack(null)
     transaction.commit();
    }
}

2dk2RRM2dZ8gKjXsrozapsD83FxL3Xbyyi5LFttAhrXxr16mCe4arfLHNDdHCBmaJroMz2VbLrf6Rxy9uPQm7Ts7EnXL4nPiXSE5vJWSfR53VcqDUrQD87CZSpt2RKZcmrYrze8KanjkfyS8XmMCcz4p33NZmfHE4S9oRo3wU2.png

Running The App

That's it guys, congratulations on implementing your first fragment activities.

This skill will come in handy when building complex Apps which require a lot of work to be done in the User Interface.

Most complex Apps have so many activities pages and features amd it's fragment activities that makes things easy for developers.

With fragment activities, each act to page inside an App would have to be a full activity that users have to click buttons to enter or open.

That would mean id an app had ten different activity pages, the user would have to open ten different activities just to get to the last actb8.

Imagine had weird and stressful that would be. This is what makes the fragments concept so important to both developers and App users.

You can run your App no either using an emulator or a physical Android device. When the App launches, ensure that all the fragments activities are displayed.

That's all for today's episode guys. I hope you found this tutorial useful and helpful.

Always if you have trouble installing the required softwares, writing the code or running the finished App, please let me know in the comments.

Thank you all for the support. To my friends @stickupcurator or @stickupboys and everyone else

Have A Great Day And Catch You Next Time On StemSocial. Goodbye 👨‍💻


You Can Follow Me @skyehi For More Like This And Others



0
0
0.000
4 comments
avatar

Congratulations @skyehi! You have completed the following achievement on the Hive blockchain And have been rewarded with New badge(s)

You have been a buzzy bee and published a post every day of the week.

You can view your badges on your board and compare yourself to others in the Ranking
If you no longer want to receive notifications, reply to this comment with the word STOP

Check out our last posts:

Hive Power Up Day - February 1st 2024
0
0
0.000
avatar

Thanks for your contribution to the STEMsocial community. Feel free to join us on discord to get to know the rest of us!

Please consider delegating to the @stemsocial account (85% of the curation rewards are returned).

Thanks for including @stemsocial as a beneficiary, which gives you stronger support. 
 

0
0
0.000