DESCRIPTION
In this tutorial we will add a back button in action kafetaria , 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"><Buttonandroid:id="@+id/startActBtn"android:text="New Activity"android:layout_width="wrap_content"android:layout_height="wrap_content" /></LinearLayout>
MainActivity.kt
package com.blogspot.devofandroid.myapplicationimport android.content.Intentimport android.support.v7.app.AppCompatActivityimport android.os.Bundleimport android.widget.Buttonclass MainActivity : AppCompatActivity() {override fun onCreate(savedInstanceState: Bundle?) {super.onCreate(savedInstanceState)setContentView(R.layout.activity_main)//buttonval mStartActBtn = findViewById<Button>(R.id.startActBtn)//handle button clickmStartActBtn.setOnClickListener {//start activity intentstartActivity(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"><TextViewandroid:text="Click back buttoon of actionbar"android:layout_width="wrap_content"android:layout_height="wrap_content" /></LinearLayout>
NewActivity.kt
package com.blogspot.devofandroid.myapplicationimport android.support.v7.app.AppCompatActivityimport android.os.Bundleclass NewActivity : AppCompatActivity() {override fun onCreate(savedInstanceState: Bundle?) {super.onCreate(savedInstanceState)setContentView(R.layout.activity_new)//actionbarval actionbar = supportActionBar//set actionbar titleactionbar!!.title = "New Activity"//set back buttonactionbar.setDisplayHomeAsUpEnabled(true)actionbar.setDisplayHomeAsUpEnabled(true)}override fun onSupportNavigateUp(): Boolean {onBackPressed()return true}}
Step 4: Run Project
Output
0 Response to "Add A Back Button To Action Kafe Android Studio (Kotlin)"