What is Fragment in Android Studio |How to Use Fragment

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 :

How To Create Awesome Menu Icon in Android[2020]

Welcome to our new post, In this post, we are going to learn how to create a menu Icon in android. If you are new to android development I recommend reading my other blog as well.
By the end of this post, you will able to create this type of menu Icon

Before starting the tutorial, What we are using for creating menu Icon is Android studio IDE, Emulator or real device for testing. So, let’s start our tutorial

Steps to create Menu Icon

Disabling Action Bar

Firstly, we need to remove the default action bar, and then we attach our ready-made toolbar to the app. So go to the Android then res and then values and then styles.xml

Android -> res -> values ->styles.xml

and then Change your parent theme to

Theme.AppCompat.Light.NoActionBar

Your styles.xml should look like this after do changing

<resources>

    <!-- Base application theme. -->
    <style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
        <!-- Customize your theme here. -->
        <item name="colorPrimary">@color/colorPrimary</item>
        <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
        <item name="colorAccent">@color/colorAccent</item>
    </style>

</resources>

Now, we need to create a custom toolbar. Follow second step

Creating Menu Resource file

Now we need to create a menu resource file where we add menu items that we are using in the toolbar. Yes, First we create a menu file then items, and then we create a toolbar, and then we add a menu item in Toolbar.

So, go to the res then right-click and then new and then Android resource file and select menu from values column and give it any name. The menu folder contains all icons of the toolbar or navigation header.

res -> right click -> new -> Android resource file

creating menu file
Creating menu file

Creating Menu Icons

Now, we need to create some icons that we used in our menu. In this post I am going to create the 3 menu icons first is cart Icon second is Download and third is Log Out.

Now go to res folder then right click and then new and then vector asset, then pop up will open and click on clip art twice.

Now choose any three icons you want to show on the Toolbar menu. Here I am choosing these Icons

creating menu icons
creating menu icons

Adding Menu Items In Resource file

After creating the menu file and Menu Icons we need to add items in the menu file.

Creating menu items is very easy all you need to do is go to res then menu directory and then double click on our menu file. Now add following line of code

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto">

    <item
        android:id="@+id/cart"
        android:title="Cart"
        android:icon="@drawable/locj"
        android:orderInCategory="1"
        app:showAsAction="ifRoom"/>
    <item
        android:id="@+id/on_way_status"
        android:title="Status"
        android:icon="@drawable/ic_assignment_returned_black_24dp"
        android:orderInCategory="1"
        app:showAsAction="ifRoom"/>
    <item
        android:id="@+id/log_out"
        android:title="Log Out"
        android:icon="@drawable/logout"
        android:orderInCategory="1"
        app:showAsAction="ifRoom"/>

</menu>

Explanation of Menu Item Code

Now, you will able to see following view in design view of android studio. But do you understand all the stuff.

Let me explain each line of code. The first parent tag is the menu under which we add our menu Items. Then we add three-item tag which represents the three items that we are using in our toolbar

<item
        android:id="@+id/cart"
        android:title="Cart"
        android:icon="@drawable/locj"
        android:orderInCategory="1"
        app:showAsAction="ifRoom"/>

First we add id to our item and then we give item a name by using

 android:title="Cart"

Then we give icon to our menu item as we created above using

android:icon="@drawable/locj"

locj is name of icon and drawable is folder where icon is present and then we use

 android:orderInCategory="1"

android:orderInCategory is an integer attribute that dictates the order in which the menu items will appear within the menu when it is displayed.

app:showAsAction="ifRoom"

This means only place this item in the app bar if there is room for it. If there is not room for all the items marked “ifRoom“, the items with the lowest orderInCategory values are displayed as actions, and the remaining items are displayed in the overflow menu

Creating Custom Toolbar

Now more than half of our work is completed, We need to create a toolbar and add our menu to toolbar. This is very easy and all you need to do is go to your activity_main.xml and paste this code.

  <androidx.appcompat.widget.Toolbar
        android:layout_width="match_parent"
        android:layout_height="?attr/actionBarSize"
        android:id="@+id/toolbar"
        app:titleTextColor="#FFFFFF"
        android:background="#FF5722"
        app:menu="@menu/menu_toolbar" 
        android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"/>

Don’t worry, We explain each line of this code

Explanation of Custom Toolbar Code

What we have done is added a toolbar using this

<androidx.appcompat.widget.Toolbar/>

We set the width of the toolbar to width parent which means toolbar is going to fit with the width of the phone

android:layout_width="match_parent"

Then we set the height of toolbar equals to the height of action bar using the following line of code

android:layout_height="?attr/actionBarSize"

Now we give id to our toolbar and give a text color to our menu items and also give background

android:id="@+id/toolbar"
app:titleTextColor="#FFFFFF"
 android:background="#FF5722"

We set the menu resource file to the toolbar and then theme using the following line of command

app:menu="@menu/menu_toolbar" 
android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"

Connecting Toolbar via Java code

Now, we are ready to attach our toolbar via java code. Go to your MainActivity.java file and then Create toolbar and action bar variable like this

 Toolbar toolbar;
    ActionBar actionBar;

Now, Inside your oncreate() method add this

toolbar = findViewById(R.id.toolbar);

setSupportActionBar(toolbar);
menu options
Menu Options

This add your toolbar as action bar. Till now we know, “how to create menu icon in android “

Click Listener on Menu Items

Now, you are able to see the items in the toolbar. But when you try to click them they don’t respond. We are going to sort out this.

You need to override two methods.

First Method is onCreateOptionsMenu() where you inflate your Menu Item like this in the MainActivity.java file

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

“Inflating” a view means taking the layout XML and parsing it to create the view and view group objects from the elements and their attributes specified within and then adding the hierarchy of those views and view groups to the parent ViewGroup.

Only we need to override the onOptionsItemSelected() method. This method called whenever an item from the menu is clicked.

@Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle item selection
        switch (item.getItemId()) {
            case R.id.cart:
               Log.d("cehck","In Search");
                return true;
            case R.id.log_out:
                      Toast.makeText(getApplicationContext(),"Profile",Toast.LENGTH_SHORT).show();
                return true;
            default:
                return super.onOptionsItemSelected(item);
        }
    }

Whenever you click any menu item, Android calls onOptionsMenu(), and then it matched Id of the menu item that is pressed with all items using switch statement and executes the code of case when it matches.

Conclusion

Finally, we learn how to create menu icon in android and attaching click listener to it. You can learn more about Toolbar here

Tagged :

Android Line Chart-How To Draw Line Chart In Android Studio[2020]

Hi, In this post we are going to learn, How to draw a line chart in the android studio. The Line chart is very important for data analysis because it is easy to understand.

We can create a Line chart by using MP Android chart dependency. MP Android chart is an easy and powerful way to design many types of charts.

As we previously discussed how to create a pie chart in android studio using MP Android chart.

Without wasting your time, we are going to explain to you how to make charts.

Draw a Line Chart In Android Studio

Step 1: Adding Dependency

The first things you need to do is to add the dependency.

Dependencies allow us to include an external library or local jar files or other library modules in Android project

Go to Android then build.gradle(Module: app) and add this inside dependency.

dependencies {
 implementation 'com.github.PhilJay:MPAndroidChart:v3.1.0'
}

Now add following line of code in your repository in build.gradle(Project: App Name)

allprojects {
    repositories {
        google()
        jcenter()
        maven { url 'https://jitpack.io' } // add line which is not present
        
    }
}

Till now, we included the dependency of the chart and we are set to go start making our line chart. Now sync your project.

Step 2: Adding Line Chart in .xml

After we add a dependency, our second step is to add the pie chart in .xml. MP Android chart provide us many types of the chart such as Pie, Line, Bar Curve, etc.

<com.github.mikephil.charting.charts.LineChart
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/lineChart"/>

Step 3: Adding values in Line Chart

After adding line chart in xml we need to pass data in line chart, we do this in java file by using following code

public class MainActivity extends AppCompatActivity {

LineChart lineChart;
LineData lineData;
List<Entry> entryList = new ArrayList<>();
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        lineChart = findViewById(R.id.lineChart);
        entryList.add(new Entry(10,20));
        entryList.add(new Entry(5,10));
        entryList.add(new Entry(7,31));
        entryList.add(new Entry(3,14));
        LineDataSet lineDataSet = new LineDataSet(entryList,"country");
        lineDataSet.setColors(ColorTemplate.JOYFUL_COLORS);
        lineDataSet.setFillAlpha(110);
        lineData = new LineData(lineDataSet);
        lineChart.setData(lineData);
        lineChart.setVisibleXRangeMaximum(10);
        lineChart.invalidate();

    }

}

If you read our previous post, you will able to understand each line of code without explanation, But again we are going to explain you.

First, we create a reference variable of the Line chart, Line data. We also create a list of Entry by following the line of code.

LineChart lineChart;
LineData lineData;
List<Entry> entryList = new ArrayList<>();

Line chart uses line data to represent values, and line Data uses a list of entries to represent values.

After this inside onCreate() we connect the Line chart to its XML view.

lineChart = findViewById(R.id.lineChart);

Now we add our data to the entry list by creating an object of Entry and passing x and y to its constructor.

        entryList.add(new Entry(10,20));
        entryList.add(new Entry(5,10));
        entryList.add(new Entry(7,31));
        entryList.add(new Entry(3,14));

Finally we create a line data set and attach to line chart by this code

        LineDataSet lineDataSet = new LineDataSet(entryList,"country");
        lineDataSet.setColors(ColorTemplate.JOYFUL_COLORS);
        lineDataSet.setFillAlpha(110);
        lineData = new LineData(lineDataSet);
        lineChart.setData(lineData);
        lineChart.setVisibleXRangeMaximum(10);
        lineChart.invalidate();

setData() sets the data and invalidate() is used if we update our values then it automatically changes the values in the pie chart.

If you run your code you see something like this

line chart in android studio

Conclusion

I hope you learn How to draw line chart in android studio from this post. If you find this helpful please share this article and comment if any error persist in the code

Tagged : /

How To Add Back Button in Android Title Bar[2020]

In this post, we are going to learn how to add back button in android title bar. Adding the Back button in the Title bar is very easy. what we learn is adding a back button and customizing the back button also.

So let’s get Started.

Adding back button in android Studio

Step 1: Creating Project

Open Android Studio and Create new project

Step 2: Creating Activity

Go to File then New and then Activity and then Blank Activity.

Let me explain you’re the reason behind the second activity, In our main activity, we add the back button in the Title bar, and on clicking the back button we go to Second Activity.

Let’s give the name of the second activity as BackActivity.

Step 3: Adding Back Button

Now, Add the back button in android title bar by using Action Bar like this.

import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.app.ActionBar;
import android.os.Bundle;

public class MainActivity extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ActionBar actionBar = getSupportActionBar();
        actionBar.setDisplayHomeAsUpEnabled(true);
    }
}

Now, you see something like this, a back button is appearing in your toolbar. What we done is simply get the Action Bar and set the Up button enabled using setDisplayHomeAsUpEnabled(true);

back button in android studio
back button in android studio

Adding Click Listener in Back Button

Adding Click Listener on the back button is a very easy task, all you need to simply override a method and code which you want to execute on clicking Back Button.

We are going to show a Toast whenever a back button is pressed.

Step:1 Overriding Method

Override onOptionsItemSelectedMethod like below code

 @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {
        return super.onOptionsItemSelected(item);
    }

Step 2 : Showing a Toast

Now, we need to show a toast whenever the back button is pressed and we done like this, complete code is given below.


import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.app.ActionBar;
import android.os.Bundle;
import android.view.MenuItem;
public class MainActivity extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ActionBar actionBar = getSupportActionBar();
        actionBar.setDisplayHomeAsUpEnabled(true);
    }
    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {
     Toast.makeText(getApplicationContext(),"Back Button Clicked",Toast.LENGTH_SHORT).show();
     
        return super.onOptionsItemSelected(item);
    }
}
showing toast when back button clicked
showing toast

Step 3: Starting BackActivity whenever Back Button clicked

Now, we start back activity whenever the back button is clicked through Intent.

We do this by simply adding Intent, like this



import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import androidx.appcompat.app.ActionBar;

import android.content.Intent;
import android.os.Bundle;
import android.view.MenuItem;
import android.widget.Toast;


public class MainActivity extends AppCompatActivity {


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ActionBar actionBar = getSupportActionBar();
        actionBar.setDisplayHomeAsUpEnabled(true);
    }

    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {
        startActivity(new Intent(MainActivity.this,BackActivity.class));
        return super.onOptionsItemSelected(item);

    }
}

Also after Back Activity started we need to show a toast that Back Activity starts and we do this by adding toast in backactivity.java file.



import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.widget.Toast;

public class BackActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_back);
        Toast.makeText(getApplicationContext(),"Back Activity",Toast.LENGTH_SHORT).show();
    }
}

Now run your app and you see some thing like this

start activity throuh back
start activity throuh back

Changing Colour Of back button

If you want to customize the color of the back button you can easily do this by adding a new Arrow icon. You can do this by following steps

Step 1: Adding New Drawable

Go to file then new and then vector asset and search for arrow icon and add to your drawable folder. Screenshots attached

adding drawable
adding drawable
adding drawable
adding drawable

Step 2: Set drawable as back button

Set the created drawable as back button by following code

   @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ActionBar actionBar = getSupportActionBar();
        actionBar.setDisplayHomeAsUpEnabled(true);
        actionBar.setHomeAsUpIndicator(R.drawable.ic_arrow_back_black_24dp);
    }

Now you see your app like this

customized back button
customized back button

Conclusion

You learn how to add Back button in android title bar, attaching click listener, and also customizing icon. Hope you learn and comment if it works for you

Tagged :

Toast In Android Studio

Toast in the android studio provides you a simple interface of any feedback or operation done. Assume you developed a social media app and want to show welcome to the user whenever the user logs in, So you can use Toast to show this.

Toast in the android studio provides simple feedback in the form of popup. Read about List View Here

One of the best things of toast is it covers only the amount of space required to show the message.

But the bad part about the toast is you can not implement click listener on toast.

Toast automatically disappears after some time after showing a message on the screen.

In this post we are going to see each and every function of toast in android studio

Creating Toast in Android Studio

Creating Toast in the android studio is very simple, All you need to do is just use Toast.make text() function like this,

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
       Toast toast =  Toast.makeText(getApplicationContext(),"GeeksToCode",Toast.L ENGTH_SHORT);
       toast.show();
    }
}
Toast In Android Studio

We instantiate the Toast object with makeText() method and pass three argument’s

Context: It allows access to application-specific resources and classes, as well as up-calls for application-level operations, such as launching activities, broadcasting and receiving intents

String: This is the message you want to show in the toast

Duration: Duration up to which you want to show the Toast. Basically there is two duration present one is LENGTH_SHORT and the other is LENGTH_LONG.

Changing Position of Toast in Android studio

By Default, the toast will be shown always in the center of the bottom but the best thing is that you can change your toast position.

Changing the toast position is very simple by using the setGravity() method.

You can change toast position like this

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.view.Gravity;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
       Toast toast =  Toast.makeText(getApplicationContext(),"GeeksToCode",Toast.LENGTH_SHORT);
       toast.setGravity(Gravity.TOP,10,10);
       toast.show();
    }
}

Now, when you run this program you will see something like this,

Toast in Android Studio
Toast in Android Studio

Toast is shown in the top position at the center.

Toast.setGravity() takes three parameter which is explained below

Gravity: Gravity of toast

xOffSet: X co-ordinate of toast

yOffSet: Y co-ordinate of toast

Custom Toast in Android Studio

Android studio provides you a way to design your custom toast and use it as you want.

Designing a custom toast is very easy, all you need to create a new layout resource file and use it as toast.

Don’t worry we explain it to you step by step. Firstly Right-click on layout and then new and then Layout Resource File

Name Resource file as custom_toast.xml, now, Add following code to the .xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent">
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="GeeksToCode"
        android:layout_margin="20dp"
        android:textSize="30dp"
        android:layout_gravity="center"
        android:textColor="@color/colorPrimary"/>

</LinearLayout>

So, what we do is simply add a text view which we will be used to show the message. We set text as GeeksToCode and also give text size and text color.

Now, we need to use this layout as custom toast, for this, we need to Create a Toast object and set this layout as a view for Toast like this.

import androidx.appcompat.app.AppCompatActivity;

import android.content.Context;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toast toast = new Toast(getApplicationContext());
        toast.setDuration(Toast.LENGTH_LONG);

        LayoutInflater inflater = (LayoutInflater) getApplicationContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View view = inflater.inflate(R.layout.custom_toast, null);
        toast.setView(view);
        toast.show();
    }
}
Custom Toast in Android Studio

First we create object of Toast by this line of code

 Toast toast = new Toast(getApplicationContext());

Then we set the duration to Long using this

toast.setDuration(Toast.LENGTH_LONG);

After this, we inflate our custom_toast to view using LayoutInflater

LayoutInflater inflater = (LayoutInflater) getApplicationContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View view = inflater.inflate(R.layout.custom_toast, null);

Now, we simply add the view to Toast by using this method and show it to the user.

toast.setView(view);
        toast.show();

Adding Image in Toast

We know how to create a Toast and now we are going to know How to insert Image in Toast. Inserting Image in Toast is quite easy because we learn previously creating custom Toast.

What I need to do is simply add an Image View in the custom_toast and then attach it to the Toast.

First right click on drawable and click new and then vector assets. Choose any of the icons and add them. I use the ac unit icon.

The following code is for the adding image in custom_toast

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="horizontal" android:layout_width="match_parent"

    android:layout_height="match_parent">

    <ImageView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@drawable/ic_ac_unit_black_24dp"/>
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
       android:layout_marginLeft="5dp"
        android:text="GeeksToCode"
        android:textColor="@color/colorPrimary"
        android:textSize="30dp" />

</LinearLayout>

I set LinearLayout orientation to horizontal so Our toast looks beautiful. Now we only need to add this in our Toast like we add above

import android.content.Context;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toast toast = new Toast(getApplicationContext());
        toast.setDuration(Toast.LENGTH_LONG);

        LayoutInflater inflater = (LayoutInflater) getApplicationContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View view = inflater.inflate(R.layout.custom_toast, null);
        toast.setView(view);
        toast.show();
    }
}

After running this you will see screen like this

Image in Toast in Android Studio

Conclusion:

So, after reading whole of this content you know what is Toast, How to make custom Toast and also How to add image in Toast. So Run this code in your own android studio and let me know If it helps you.

You can refer this docs also.

Tagged : /