Android Fragment.


Android Fragment Tutorial and Examples.

Quick Android Fragment Examples and HowTo's

1. How to Replace a Fragment Using FragmentTransaction

Yeah, we can easily replace a fragment via FragmentTransaction.

But first we need a placeholder where the Fragment will be inserted within our activity.

So for example if you have a layout like activity_main.xml, then within that layout add a placeholder like this:

<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/drawer_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:clickable="true">
        ......
        <FrameLayout
            android:id="@+id/main_frame"
            android:layout_weight="1"
            android:layout_width="match_parent"
            android:layout_height="0dp">
            .....
</android.support.v4.widget.DrawerLayout>

So in our case we've used the framelayout, however you can use any layout.

All we need is a place where our Fragment will be rendered and FrameLayout is perfect for that.

Then we proceed to our java code.

Let's create a method that will receive a Fragment object as a parameter.

We'll then start by retrieving the FragmentManager using the getSupportFragmentManager() method of the activity.

Then calling the beginTransaction() of that FragmentManager will give us a FragmentTransaction instance.

Then we can use that FragmentTransaction to replace the FrameLayout we defined above with our Fragment using the replace() method.

Then we make sure we commit that Transaction.

    private void replaceFragmentAnimation(Fragment fragment) {

        FragmentManager manager = getSupportFragmentManager();
        FragmentTransaction transaction = manager.beginTransaction();
        transaction.replace(R.id.main_frame, fragment);
        transaction.commit();

    }
2. How to Replace a Fragment with Animation Transitions

You may want to show animations, or page transitions as you replace or navigate to Fragments. Normally FragmentTransaction class is what allows us replace Fragments and we've seen how to do that.

Now let's see how to use animations as we transit to a Fragment.

First we need to define an animation resource file. In your res directory add another directory called anim.

Then create the following xml animation files in that anim directory;

slide_left_in.xml

<?xml version="1.0" encoding="utf-8"?>
<!--Slide from left to right-->
<set xmlns:android="http://schemas.android.com/apk/res/android"
    android:fillAfter="true">

    <translate
        android:duration="200"
        android:fromXDelta="-100%p"
        android:toXDelta="0"/>
</set>

slide_left_out.xml


<?xml version="1.0" encoding="utf-8"?>
<!--Slide out from right to left-->
<set xmlns:android="http://schemas.android.com/apk/res/android">
    <translate
        android:duration="200"
        android:fromXDelta="0"
        android:toXDelta="-100%p"/>
</set>

slide_right_in.xml

<?xml version="1.0" encoding="utf-8"?>
<!--Slide from right to left-->
<set xmlns:android="http://schemas.android.com/apk/res/android"
    android:fillAfter="true">

    <translate
        android:duration="200"
        android:fromXDelta="100%p"
        android:toXDelta="0"/>
</set>

slide_right_out.xml

<?xml version="1.0" encoding="utf-8"?>
<!--Slide out from left to right-->
<set xmlns:android="http://schemas.android.com/apk/res/android">
    <translate
        android:duration="200"
        android:fromXDelta="0"
        android:toXDelta="100%p"/>
</set>

Then inside your activity as class fields have the following constants:

 Private final int SLIDE_FROM_LEFT_TO_RIGHT = 0 ; //Sliding the page from left to right 
 private final int SLIDE_FROM_RIGHT_TO_LEFT = 1 ; // Swing the page's animation from right to left   

Then within a method inside your activity:

    private void replaceFragment(Fragment fragment, int slideType) {

        FragmentManager manager = getSupportFragmentManager();
        FragmentTransaction transaction = manager.beginTransaction();

        switch (slideType){
            case SLIDE_FROM_LEFT_TO_RIGHT:
                transaction.setCustomAnimations(R.anim.slide_left_in,R.anim.slide_right_out);
                break;
            case SLIDE_FROM_RIGHT_TO_LEFT:
                transaction.setCustomAnimations(R.anim.slide_right_in,R.anim.slide_left_out);
                break;
        }

        transaction.replace(R.id.main_frame, fragment);
        transaction.commit();

        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                //maybe activate some buttons or something else
            }
        }, 200);
    }

You can see this time our method has received a Fragment as well as an integer to identify the type of sliding animation we want to make.

Then you can use that method like this:

    replaceFragment(orderFragment, SLIDE_FROM_LEFT_TO_RIGHT);

Top Android Fragment Examples

Let's look at some examples.

The idea of dialogs is great because we can pop them out from nowhere. The user can then perform his thing then dismiss the dialog.

In this example we create a dialogfragment that gets displayed when a simple button is clicked from our main activity.

Our dialogfragment will contain a simple ListView and a SearchView. The ListView will contain a List of players.

The searchview can then be used to search the players from the list.

In this simple example here,we shall be seeing how to perform a fragment transaction on dynamic fragments.

By dynamic we mean that our Fragments get created programmatically at runtime as opposed to using XML Layouts.

We shall simply replace our layout with two fragments,each with its own layout and with simple ListViews.Take note our fragments are created dynamically on code,then we replace them and commit the transaction.

Android Fragments Tab Navigation

Have you ever had these types of scenaries which make you wonder how the world we live in is beautiful amidst the chaos of outer space.I was sitting just across my local University stadium yesterday at looking on as workers made the last touches on the pitch.The ne...

This is an android ListFragment tutorial.A ListFragment can show a ListView by default.Our ListView is going to be a custom one containing both images and text.

A DialogFragment is a fragment that displays a dialog window, floating on top of its activity's window.

This fragment contains a Dialog object, which it displays as appropriate based on the fragment's state. Control of the dialog (deciding when to show, hide, dismiss it) should be done through the API here, not with direct calls on the dialog.

We do inherit from this class(android.support.v4.app.DialogFragment) then implement the Fragment.onCreateView(LayoutInflater, ViewGroup, Bundle) to supply the content of the dialogfragment.

You can also override onCreateDialog(Bundle) to create an entirely custom dialog, such as an AlertDialog, with its own content.

This example will show a recyclerview in diaogfragment.

When the user clicks a show button we open a dialogfragment, displaying a RecyclerView on it.

When you mention the term transaction the first thing that probably comes to mind is finance. Making financial transactions in your bank or something like that.

The noun transaction_ comes from the verb transact. The verb transact was based on the Latin language term transigere which is dated 1500-1600 and means to drive throgh or to carry to completion or to finish according to Merriam-Webster's Collegiate Dictionary.

However that term is not limited to business or financial transaction only.

We can also transact fragments, or do a Fragment Transaction instead of a Business Transaction. And this basically means carrying a set of operations on Fragments.

Android Framework provides us with a set of APIs that allow us to complete these Fragment Transactions.

These APIs are encapuslated in a class called FragmentTransaction. FragmentTransaction was added in API level 1 of android. That class is class. This basically means that it provides generalizations to it's subclasses and is not exactly a concrete class itself.

Best Regards, Oclemy.

How do You Feel after reading this?

According to scientists, we humans have 8 primary innate emotions: joy, acceptance, fear, surprise, sadness, disgust, anger, and anticipation. Feel free to tell us how you feel about this article using these emotes or via the comment section. This feedback helps us gauge our progress.

Help me Grow.

I set myself some growth ambitions I desire to achieve by this year's end regarding this website and my youtube channel. Am halfway. Help me reach them by:




Recommendations


What do You Think


Previous Post Next Post