In this tutorial we will add a back button in action kafe , 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...
Step 1: Create a new Project of open existing project:
Step 2: 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/button"android:text="New Activity"android:layout_width="wrap_content"android:layout_height="wrap_content" /></LinearLayout>
Step 3: MainActivity.java
package com.blogspot.devofandroid.myapplication;import android.content.Intent;import android.os.Bundle;import android.support.v7.app.AppCompatActivity;import android.view.View;import android.widget.Button;public class MainActivity extends AppCompatActivity {@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);Button button = (Button)findViewById(R.id.button);button.setOnClickListener(new View.OnClickListener() {@Overridepublic void onClick(View view) {startActivity(new Intent(MainActivity.this , NewActivity.class));}});}}
Step 4: 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>
Step 5: NewActivity.java
package com.blogspot.devofandroid.myapplication;import android.support.v7.app.ActionBar;import android.support.v7.app.AppCompatActivity;import android.os.Bundle;public class NewActivity extends AppCompatActivity {@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_new);//actionbarActionBar actionBar = getSupportActionBar();//set actionbar title(Optional)actionBar.setTitle("New Activity");//set back buttonactionBar.setDisplayHomeAsUpEnabled(true);actionBar.setDisplayShowHomeEnabled(true);}//handle onBack pressed(go previous activity)@Overridepublic boolean onSupportNavigateUp() {onBackPressed();return true;}}
0 Response to "Add A Back Button To Action Kafe Android Studio"