Skip to main content

Action Bar with Back press Enabled Button


Action bar With Back Press Enabled Button
There are only three things we need to do, to achieve this objective.

  1.    Create action Bar with back button
  2.    Coding on Back button
  3.     And few changes in Manifest file




1.     Create action Bar with Button:
In OnCreate() method write below given lines:

getActionBar().setDisplayHomeAsUpEnabled(true);


that’s it. In OnCreate() method we just need to write this line and this will start showing back button on actionbar. But it will not perform anything until we implement ONOptionsItemSeleted() Method. Which is our step two.

2.     Coding on Back Button

@Override
            public boolean onOptionsItemSelected(MenuItem item) {
                        // TODO Auto-generated method stub
                       
                        switch(item.getItemId()){
                        case android.R.id.home:
                                    Intent upIntent = NavUtils.getParentActivityIntent(this);
                                    if(NavUtils.shouldUpRecreateTask(this, upIntent))
                                    {
                                                TaskStackBuilder.create(this).addNextIntentWithParentStack(upIntent).startActivities();
                                    }
                                    else{
                                                NavUtils.navigateUpTo(this, upIntent);



                                    }
                                 return true;
                                   
                        }                      
                       
                        return super.onOptionsItemSelected(item);
                       
                        }
Now, ONclick of back button, application will be navigated to the parent. Last final step, defining parent activity in manifest file.


3.     Make Changes in the Manifest file:

In the sub activity we need to add fews lines to tell compiler about navigation

 <activity
            android:name="com.example.actionba.MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity
            android:name="com.example.actionba.SecondActivity"
            android:label="@string/title_activity_second"
            android:parentActivityName="com.example.actionba.MainActivity" >
        </activity>

Either we need to write
android:parentActivityName=”….”
                                    Or
<meta-data
           android:name="android.support.PARENT_ACTIVITY"
           android:value="com.example.actionba.MainActivity" />

Because 4.0 and lower versions doesn’t support
android:parentActivityName="com.example.actionba.MainActivity">


Here Goes the Complete Code for this:


MainActivity.java




package com.example.actionba;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;

public class MainActivity extends Activity {

    Button button;
@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        
        button= (Button)findViewById(R.id.button1);
        button.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
startActivity(new Intent(getApplicationContext(),SecondActivity.class));
Toast.makeText(getApplicationContext(), "Secnod Activity", Toast.LENGTH_LONG).show();
}
});

}


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }
    
}


activity_main.xml


<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/LinearLayout1"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity" >

    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:layout_marginTop="170dp"
        android:text="@string/Button" />

</LinearLayout>


SecondActivity.java



package com.example.actionba;

import android.app.Activity;
import android.app.TaskStackBuilder;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.NavUtils;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Toast;

public class SecondActivity extends Activity {

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
      getActionBar().setDisplayHomeAsUpEnabled(true);
      
 
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
// TODO Auto-generated method stub
switch(item.getItemId()){
case android.R.id.home:
Intent upIntent = NavUtils.getParentActivityIntent(this);
Toast.makeText(getApplicationContext(), "We are in Home Activity", Toast.LENGTH_LONG).show();
if(NavUtils.shouldUpRecreateTask(this, upIntent))
{
TaskStackBuilder.create(this).addNextIntentWithParentStack(upIntent).startActivities();
}
else
{
NavUtils.navigateUpTo(this, upIntent);
}
return true;
}
return super.onOptionsItemSelected(item);
}

}



activity_second.xml



<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/LinearLayout1"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".SecondActivity" >

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:layout_marginTop="170dp"
        android:textSize="20sp"
        
        android:text="@string/hello_world" />

</LinearLayout>


AndroidManifest.xml



<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.actionba"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="18" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.example.actionba.MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity
            android:name="com.example.actionba.SecondActivity"
            android:label="@string/title_activity_second"
            android:parentActivityName="com.example.actionba.MainActivity" >
        </activity>
    </application>

</manifest>


Output:










Comments

Popular posts from this blog

Android: Login Screen using Fragments

In this tutorial, our focus is on making a User/Member login activity using fragments. With the help of Fragments we will use the same activity to show User login area and also Members Login area. Prerequisite for this tutorial: You should be know how to make an Activity And most importantly you should have prior Knowledge of Fragments. For practising basic Fragment implementation refer to Android Simple Fragment Example      We have used only three activities for this: MainActivity(which represents the Login Screen) Fragments for Members area Fragment for New Users

Simple Login/Register Example using SQLite database

MainActivity.java(login Screen) package com.AndroidDevelopmentGuru.database_new; import java.util.List; import android.app.Activity; import android.content.Intent; import android.database.Cursor; import android.os.Bundle; import android.view.MenuItem; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; public class MainActivity extends Activity {                                 EditText user, pass;                 Button login, not_reg;                 DatabaseHandler db;                 Cursor cursor;                                 @Override                 protected void onCreate(Bundle savedInstanceState) {                                 super.onCreate(savedInstanceState);                                 setContentView(R.layout.activity_main);

Android: Current Location Using Fused APi on Google Maps

This tutorial gives us the simple implementation of "Fused API" to fetch the current location on google map in android. Fused API is latest among all techniques to get the location. It provides you very precise results and also uses less battery of your device. It chooses GPS or Network provider to get to your current location. And it helps your device remember about the last saved location. Let's implement the Fused API to fetch/get the current location. Step 1: Create a new project in Android studio. and select Maps Activity.