Add a Back Button to Action Bar Android Studio (Kotlin)
DESCRIPTION
In this tutorial we will add a back button in action bar, when it is clicked it will go to previous activity(the app will close if this was launcher activity). We will go from main activity to new activity by clicking button in main activity. In new activity we will add a back button to actionbar when that button is clicked the main activity will appear...VIDEO
SOURCE CODE
Step 1: Create a new Project or open new project
Step 2: Create New Activity File>New>Activity>EmptyActivity
Step 3: Code:
activity_main.xml
<?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:gravity="center" tools:context=".MainActivity"> <Button android:id="@+id/startActBtn" android:text="New Activity" android:layout_width="wrap_content" android:layout_height="wrap_content" /> </LinearLayout>
MainActivity.kt
package com.blogspot.devofandroid.myapplication import android.content.Intent import android.support.v7.app.AppCompatActivity import android.os.Bundle import android.widget.Button class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) //button val mStartActBtn = findViewById<Button>(R.id.startActBtn) //handle button click mStartActBtn.setOnClickListener { //start activity intent startActivity(Intent(this@MainActivity, NewActivity::class.java)) } } }
activity_new.xml
<?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:gravity="center" tools:context=".NewActivity"> <TextView android:text="Click back buttoon of actionbar" android:layout_width="wrap_content" android:layout_height="wrap_content" /> </LinearLayout>
NewActivity.kt
package com.blogspot.devofandroid.myapplication import android.support.v7.app.AppCompatActivity import android.os.Bundle class NewActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_new) //actionbar val actionbar = supportActionBar //set actionbar title actionbar!!.title = "New Activity" //set back button actionbar.setDisplayHomeAsUpEnabled(true) actionbar.setDisplayHomeAsUpEnabled(true) } override fun onSupportNavigateUp(): Boolean { onBackPressed() return true } }
Step 4: Run Project
Output
Comments
Post a Comment