How to implement back button on an Action Bar using Kotlin

 

Back button which is normally referred to as a back arrow enables users of your app to navigate back to the previous Activities or Fragments that they have previously opened but weren't terminated (finished). It's a super cool functionality which you gotta implement to ensure effective navigation on your app, so you really should not miss placing Back button to your app’s interface.

Mobile phones have got this tendency of keeping track of destinations as the user moves around throughout your application. Through this behavior, we are then able to fallback to these destinations that the user once was, provided that they were not terminated. However, there are a few cases where your app might need to implement its own Back behavior in order to provide the best possible user experience. It makes a more perfect sense to implement a back button on an Action Bar if your project has more than one Activity. So that back arrow you normally see at one end of an action bar is normally a vector you gotta have in your drawable folder.

Am going to split this tutorial into two main segments, in both am going to implement the same stuff but with two different approaches 

Approach number One 

This approach is going to base with setting up a back button on an action bar with the current working theme of your app having ActionBar already available

Approach number Two  

In this one am going to set up an action bar back arrow with a theme that has no an action bar with it. So in this second one, we are going to employ a toolbar in place. This means that, in your XML layout you have to have a toolbar as the first thing. Let's get started...

Approach number one

 I assume you already have  created a vector asset you wanna use for this action, if you have not, please make sure you have this as earlier as possible. We gonna need it. Again as i said, this approach is most suitable for a default theme all projects comes with, having Action bar not tempered with.

  • On your activitie's onCreate method, you gonna go ahead and access the action bar simply by typing in supportActionBar. Use this and enable a feature strangely termed home as up.

    supportActionBar!!.setDisplayHomeAsUpEnabled(true)

    for safety purposes which happens to be kotlin's specialty, the supportActionBar is then wrapped up to throw a null pointer exception when a null value is detected

  • Next, we set up the indicator, which at this point it is the vector asset i have been insisting for long. You do this action and build your project, you should be able to see the back arrow on your action bar. It wont do anything to this point,  but don't worry, it's going to do what it's supposed to do. Just not now. yet.

  • supportActionBar!!.setHomeAsUpIndicator(R.drawable.back)

    Just to support what you are looking at right now, it's the safety policy i have employed again, plus my vector asset which should be available in the resources directory (more specifically in the drawables)

  • Perform an override to a method called onSupportNavigateUp(), the method returns a boolean. So this means, you gotta do all you need but at the very end, the function has to return a boolean. Luckily you will not obviously see a true or false being returned but rather a super class. Let's go ahead and see how it looks....

    override fun onSupportNavigateUp(): Boolean {
    onBackPressed()
    return super.onSupportNavigateUp()
    }

    we all are in the same page right now. We must admit that the task is easier than you thought. Finally you have a properly working back button on an action bar that works super well. If this is enough for you, that's cool but i suggest that we head over and see the second approach where we use a toolbar to implement the same thing, but differently.

    Approach number Two

    Let's keep it moving. Requirements for performing this second kind of approach is to have a toolbar somewhere in your XML layout, give it a cool id so we can access it over the .kt file. Check mine below 

    <?xml version="1.0" encoding="utf-8"?>
    <androidx.constraintlayout.widget.ConstraintLayout 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"
    tools:context=".SplasherActivity">

    <androidx.appcompat.widget.Toolbar
    android:id="@+id/softoniaBar"
    android:layout_width="match_parent"
    android:layout_height="?attr/actionBarSize"
    android:background="@drawable/background_ya_dwnldbtn"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintTop_toTopOf="parent"/>


    </androidx.constraintlayout.widget.ConstraintLayout>
That there, is an example of my dummy xml i am going to use for this illustration. I used a simple androidx toolbar, i suppose you will use the same, just to make it easier this moment.
  • Before saying anything, This approach makes more sense if you have been using a theme without an action Bar, am gonna lead the way and set up an action bar. It's like some sort of configuring a toolbar to our actionBar. Take a look at the code below, i hope you gonna visualize what am trying to say here
     
    setSupportActionBar(kiunganishi.softoniaBar)
I should be the first to say this. That strange kiunganishi you are looking at right here is strange. Like totally. But what is it?. Well it's a Swahili word that stands for anything that you can use to bind or tie something. Something is starting to be obvious right?, Am using View Binding on my activity, so that kiunganishi is the binding instance am using to access views from my screen. What i have just done is, i have accessed my toolbar, but only in a more fancier way of View Binding. I have done a couple of articles regarding view Binding. check one here
  •  This step should be super easy, coz all am gonna ask you to do is to recite the first and the second bullet from the first approach and do the same thing, but only faster and more precisely. With zero doubt, go ahead and you have to have something like this..
  • supportActionBar!!.setDisplayHomeAsUpEnabled(true)
            supportActionBar!!.setHomeAsUpIndicator(R.drawable.back)

    It's just a repetition of what we have done a couple paragraphs before. You should be having a very easy time with that.

  • Last but not least, use the binding utility you have on your activity and access the toolbar id from the screen. We gonna need it to trigger a back movement once the arrow is touched, or clicked say.

    kiunganishi.softoniaBar.setNavigationOnClickListener { onBackPressed() }

    Am not saying we should all be using View Binding, and yet it's a good practice. But if you are still using the findViewById method, that's a good thing, we all have been using that. I would not expect you to have the binding feature (kiunganishi) if you are still with the previous approach of accessing views.

Thank you for spending so much of your time with me, i really appreciate your interest with my blog, and am really thankful for that. I recently have been obsessed with action bars, so i have a number of articles about it, For example How to add an Options menu on an action bar and a lot more not so related but relevant check them out. Thank you for having me

#Sam

0 Comments