What is Fragment in Android Studio |How to Use Fragment

fragment in android studio

What is A fragment?. If you are new in android application development, you must hear about this. But don’t worry we are going to explain in detail about creating Fragment in android studio in a very easy way.

fragment in activity
fragment in android studio

At the end of this post you are able to create this type of fragment in the android studio. So why are you waiting just open your android studio and start following our steps

Fragment in android studio:

A Fragment represents a behavior or a portion of user interface in a FragmentActivity. You can combine multiple fragments in a single activity to build a multi-pane UI and reuse a fragment in multiple activities. You can think of a fragment as a modular section of an activity, which has its own lifecycle, receives its own input events, and which you can add or remove while the activity is running

Creating A Fragment in android studio

How to create A fragment. Now, first we create a fragment. Creating a fragment is very easy. All you need to Go to file then new and then Fragment. Then you see 4 types of fragments.

creating fragment in android studio
types of fragment
  • List Fragment
  • Blank Fragment
  • Fragment with view model
  • Modal Bottom Sheet

But in this post, we are going to create a blank fragment. When you click blank fragment you will see this screen.

You can also use list fragment in android studio and other. This is the same as when you create a new activity and there you see many types of activity.

Now, Uncheck the include fragment factory method because we don’t need this. What this check do is add some methods that we don’t need here.

creating fragment in android studio
fragment in anroid studio

 And make sure you check the create the layout XML file.

So your fragment’s layout is created and connected with fragment just like in activity.

And in the same way create another blank fragment and name according to you. Try to name login fragment and sign up the fragment.

Changing the Layout of fragment

Now go to the fragment_login.xml and change the layout of the fragment. We use some drawables that are taken from vector assets. If you want to learn how to create vector assets click here. Inside menu items, I tell you how to create vector assets

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:background="@android:color/black"
    tools:context=".Fragment.LogIn">

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">
    <com.google.android.material.textfield.TextInputLayout
        android:layout_width="match_parent"
        android:textColorHint="#F80000"
        android:layout_margin="20dp"
        android:layout_height="wrap_content">

        <com.google.android.material.textfield.TextInputEditText
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:id="@+id/email"
            android:textColor="#D51212"

            android:maxLines="1"
            android:maxLength="40"

            android:hint="Email"
            android:textColorHint="@android:color/holo_red_dark"
            />
    </com.google.android.material.textfield.TextInputLayout>


    <com.google.android.material.textfield.TextInputLayout
        android:layout_width="match_parent"
        android:textColorHint="#FF0000"
        android:layout_margin="20dp"
        app:passwordToggleEnabled="true"
        app:passwordToggleTint="@android:color/holo_red_dark"
       android:layout_height="wrap_content">

        <com.google.android.material.textfield.TextInputEditText
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:textColor="#D51212"
            android:hint="Password"

            android:maxLines="1"
            android:maxLength="10"
            android:id="@+id/password"

            android:inputType="textPassword"
            android:textColorHint="@android:color/holo_red_dark"
            />
    </com.google.android.material.textfield.TextInputLayout>
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="end"
        android:text="Forgot Password"

        android:textStyle="italic|bold"
        android:textSize="20sp"
        android:textColor="@android:color/white"/>

<Button
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="end"
    android:layout_margin="20dp"
    android:text="Log In"
    android:id="@+id/login"
    android:textColor="@android:color/white"
    android:background="@drawable/rounded"
    android:drawableRight="@drawable/ic_arrow_forward_black_24dp"
    android:drawableEnd="@drawable/ic_arrow_forward_black_24dp" />
    <androidx.constraintlayout.widget.ConstraintLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        >

        <ImageView
            android:layout_width="38dp"
            android:layout_height="64dp"
            android:id="@+id/phone"
            android:src="@drawable/ic_local_phone_black_24dp"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintHorizontal_bias="0.498"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toTopOf="parent"
            app:layout_constraintVertical_bias="0.802" />


    </androidx.constraintlayout.widget.ConstraintLayout>


</LinearLayout>

</FrameLayout>

And then go to fragment_signup.xml and change the layout like this.

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:background="@android:color/black"
    tools:context=".Fragment.SignUp">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical">
        <com.google.android.material.textfield.TextInputLayout
            android:layout_width="match_parent"
            android:textColorHint="#F80000"
            android:layout_margin="20dp"
            android:layout_height="wrap_content">

            <com.google.android.material.textfield.TextInputEditText
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:textColor="#D51212"
                android:id="@+id/email"

                android:maxLines="1"
                android:maxLength="40"
                android:hint="Email"
                android:textColorHint="@android:color/holo_red_dark"
                />
        </com.google.android.material.textfield.TextInputLayout>


        <com.google.android.material.textfield.TextInputLayout
            android:layout_width="match_parent"
            android:textColorHint="#F80000"
            android:layout_margin="20dp"
            app:passwordToggleEnabled="true"
           app:passwordToggleTint="@android:color/holo_red_dark"
            android:layout_height="wrap_content">

            <com.google.android.material.textfield.TextInputEditText
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:textColor="#D51212"
                android:hint="Password"

                android:maxLines="1"
                android:maxLength="10"
                android:id="@+id/password"
                android:inputType="textPassword"
                android:textColorHint="@android:color/holo_red_dark"
                />
        </com.google.android.material.textfield.TextInputLayout>
        <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="end"
            android:layout_margin="20dp"
            android:id="@+id/signup"
            android:background="@drawable/rounded"
            android:text="Sign Up"
            android:textColor="@android:color/white"
            android:drawableRight="@drawable/ic_arrow_forward_black_24dp"
            android:drawableEnd="@drawable/ic_arrow_forward_black_24dp"
            />

        <androidx.constraintlayout.widget.ConstraintLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            >

            <ImageView
                android:layout_width="38dp"
                android:layout_height="64dp"
                android:id="@+id/phone"
                android:src="@drawable/ic_local_phone_black_24dp"
                app:layout_constraintBottom_toBottomOf="parent"
                app:layout_constraintEnd_toEndOf="parent"
                app:layout_constraintHorizontal_bias="0.498"
                app:layout_constraintStart_toStartOf="parent"
                app:layout_constraintTop_toTopOf="parent"
                app:layout_constraintVertical_bias="0.802" />


        </androidx.constraintlayout.widget.ConstraintLayout>



    </LinearLayout>


</FrameLayout>

I use TextInputEditText to make UI more attractive If you don’t add this in your app then simply goto design view of fragment_main.xml and search TextInputEdit in pallet section and from there drag and drop to your app.

This automatically adds to your dependency. The main aim of this is that the app looks real.

Now login and sign up fragments are completed. I think I don’t need to explain the XML layout of this fragment.

Again goto activity_main.xml and add this line of code

<FrameLayout
        android:id="@+id/container"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
    </FrameLayout>

A-frame layout is added because we want our fragment to open in this FrameLayout

3. Starting Fragment from activity

Before using both fragments from the same activity we are going to open fragments from the main activity. So go to your mainActivity.java file add a Fragment manager like this

FragmentManager manager = getFragmentManager();
FragmentTransaction transaction = manager.beginTransaction();
transaction.add(R.id.container,new LogInFragment(),"LogIn Fragment");
transaction.addToBackStack(null);
transaction.commit();

What this code does is open the Login Fragment directly because you added the code in oncreate() method and oncreate method is the first method in the activity life cycle so fragment is started.

Fragment Life cycle.

Before going away we are going to learn fragment life cycle. The life cycle is almost the same as an activity but there is only some difference.

fragment life cycle
fragment life cycle

 As you are able to see the life cycle of fragment let me introduce to each method.

onCreate()

The Android calls this while creating the fragment. This is the same as onCreate() in Activity. Within your implementation, you should initialize the essential components of the fragment that you want to retain. when the fragment is paused or stopped, then resumed.

onCreateView()

The system calls this when it’s time for the fragment to draw its user interface for the first time. To draw a UI for your fragment, you must return a View from this method that is the root of your fragment’s layout.

onPause()

The system calls this method as the first indication that the user is leaving the fragment (though it doesn’t always mean the fragment is being destroyed). This is usually where you should commit any changes that should be persisted beyond the current user session (because the user might not come back).

Modifying  activity.main xml

Now, we are going to add both fragments in the same activity. For doing this first we are going to change the layout of main_activity layout.xml a little bit. Make your activity_main.xml look likes my code

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:background="@android:color/black"
    tools:context=".activity.Main2Activity">
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textColor="@android:color/white"
            android:layout_margin="20dp"
            android:text="Log In"
            android:textStyle="italic|bold"
            android:id="@+id/login"
            android:textSize="45sp"
/>
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_margin="20dp"
            android:textColor="@android:color/white"
            android:text="Sign Up"

            android:textStyle="italic|bold"
            android:id="@+id/signup"
            android:textSize="25sp"
            />

    </LinearLayout>



    <FrameLayout
        android:id="@+id/frameLayout"
        android:layout_width="match_parent"
        android:layout_height="match_parent"/>
</LinearLayout>

Login Textview is used so that whenever user want to login and click on login user see login fragment and whenever user click signup for signing up then user see sign up fragment.

Executing Fragments from same activity

Now, we need to attach a click listener to the text view in the layout of the activity. We also need to create a fragment manager instance, fragment transaction instance, and objects of a fragment of which we need a transaction. We do transactions using this code. Now complete code of mainactivity.java

TextView login,signup;
    FragmentManager fragmentManager;
    FragmentTransaction fragmentTransaction;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main2);
        fragmentManager = getSupportFragmentManager();
        fragmentTransaction = fragmentManager.beginTransaction();
        fragmentTransaction
                .add(R.id.frameLayout, new LogIn(), "")
                .commit();
        login = findViewById(R.id.login);

        login.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                login.setTextSize(45);
                signup.setTextSize(25);
                fragmentTransaction = fragmentManager.beginTransaction();
            
               fragmentTransaction.replace(R.id.frameLayout, new LogIn()).commit();
            }
        });

        signup = findViewById(R.id.signup);

        signup.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                signup.setTextSize(45);
                login.setTextSize(25);
                fragmentTransaction = fragmentManager.beginTransaction();
                fragmentTransaction.replace(R.id.frameLayout,new    SignUp()).commit();
                Log.d("checking","SignUp");
            }
        });



    }

When you run the app you see something like this. I hope your code also runs as mine.

fragment in activity

And when you click signup button

fragment in activity

Conclusion

Now, you know how to create a fragment in android studio. How to open a fragment from the activity and also how to replace fragments. I hope you like this post. If you like this Please comment!!

Tagged :

Leave a Reply

Your email address will not be published. Required fields are marked *