Thursday 2 April 2015

Android Action Bar


When we are targeting 3.0 or above action bar is included in all activities that use the Theme.Holo theme, which is the default theme when either the targetSdkVersion or minSdkVersion attribute is set to "11" or greater.

<manifest ... >
    <uses-sdk android:minSdkVersion="11" ... />
    ...
</manifest>

Now if we are customizing then parent should be "Theme.Holo".

Action bar support is provided for Android 2.1 and above.Include v7 appcompat library in your project to avail this feature.

Once you have the Support Library integrated with your app project:

Update your activity so that it extends ActionBarActivity.

For example:
public class MainActivity extends ActionBarActivity { ... }

In your manifest file, update either the <application> element or individual <activity> elements to use one of the Theme.AppCompat themes.

For example:
<activity android:theme="@style/Theme.AppCompat.Light" ... >

i.e is very important point.If we are targetting lower versions of android then add v7 appcompat library in your project then also in your style file change theme to :

   <style name="AppTheme" parent="Theme.AppCompat.Light">
        <!-- Customize your theme here. -->
    </style>

Else you will face a crash saying : Caused by: java.lang.IllegalStateException: You need to use a Theme.AppCompat theme (or descendant) with this activity.

Once you done all these things right your done with setting up the actionBar using support library so as to make actionbar work in all versions.below is the Code snippet :

1. MainActivity.java

public class MainActivity extends ActionBarActivity {

    android.support.v7.app.ActionBar mActionBar;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
     
    }

2. styles.xml

<resources>

    <!-- Base application theme. -->
    <style name="AppTheme" parent="Theme.AppCompat.Light">
        <!-- Customize your theme here. -->
    </style>

</resources>

3. AndroidManifest.xml

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

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name=".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>
    </application>

</manifest>

4. build.gradle

apply plugin: 'com.android.application'

android {
    compileSdkVersion 22
    buildToolsVersion "22.0.1"

    defaultConfig {
        applicationId "com.example.kamalvaid.actionbardemo"
        minSdkVersion 8
        targetSdkVersion 22
        versionCode 1
        versionName "1.0"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    compile 'com.android.support:appcompat-v7:22.+'  // Support lib for actionbar
}

}

output :



Now showing Action Buttons in the actionbar...

If you are targetting version 11 and above then just write in menu.xml :

<menu xmlns:android="http://schemas.android.com/apk/res/android" >
    <!-- Search, should appear as action button -->
    <item android:id="@+id/action_search"
          android:icon="@drawable/ic_action_search"
          android:title="@string/action_search"
          android:showAsAction="ifRoom" />
    <!-- Settings, should always be in the overflow -->
    <item android:id="@+id/action_settings"
          android:title="@string/action_settings"
          android:showAsAction="never" />
</menu>

but If you are targetting version less then 11 just write in menu.xml i.e if you are using support library:

<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:com.example.kamalvaid.actionbardemo="http://schemas.android.com/apk/res-auto"
>

    <item android:id="@+id/action_search"
        android:icon="@android:drawable/sym_action_email"
        android:title="action search"
        com.example.kamalvaid.actionbardemo:showAsAction="ifRoom"  />
    <!-- Settings, should always be in the overflow -->
    <item android:id="@+id/action_settings"
        android:title="@string/action_settings"
        com.example.kamalvaid.actionbardemo:showAsAction="ifRoom" />
</menu>

As android:showAsAction="ifRoom" is only available from 3.0 and above so you've to use your app namespace instead android as done above.

Now show inflate your actionbuttons in the action by overidding below (onCreateOptionsMenu) method :

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

Now handling clicks for action button, We need to overide below function in order to do so (onOptionsItemSelected(MenuItem item)):

 @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        switch (item.getItemId()) {
            case R.id.action_settings:
                openSettings();
                return true;
            case R.id.sym_action_email:
                openEmail();
                return true;
            default:
                return super.onOptionsItemSelected(item);
        }
    }

    private void openSettings(){
        Toast.makeText(MainActivity.this,"Open Settings here",Toast.LENGTH_LONG).show();
    }

    private void openEmail(){
        Toast.makeText(MainActivity.this,"Open Email here",Toast.LENGTH_LONG).show();
    }


output : 



Below is the full code Snippet for Action ActionButtons :

1. MainActivity.java

public class MainActivity extends ActionBarActivity {

    android.support.v7.app.ActionBar mActionBar;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        setupActionBar();
    }

    void setupActionBar(){
        //mActionBar=getSupportActionBar();
       // mActionBar.setDisplayHomeAsUpEnabled(true);
    }

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

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        switch (item.getItemId()) {
            case R.id.action_settings:
                openSettings();
                return true;
            case R.id.sym_action_email:
                openEmail();
                return true;
            default:
                return super.onOptionsItemSelected(item);
        }
    }

    private void openSettings(){
        Toast.makeText(MainActivity.this,"Open Settings here",Toast.LENGTH_LONG).show();
    }

    private void openEmail(){
        Toast.makeText(MainActivity.this,"Open Email here",Toast.LENGTH_LONG).show();
    }
}

2. strings.xml

<resources>

    <!-- Base application theme. -->
    <style name="AppTheme" parent="Theme.AppCompat.Light">
        <!-- Customize your theme here. -->
    </style>
   <!-- <style name="CustomActionBarTheme"
        parent="Theme.AppCompat.Light">
        <item name="android:actionBarStyle">@style/MyActionBar</item>
    </style>

    &lt;!&ndash; ActionBar styles &ndash;&gt;
    <style name="MyActionBar"
        parent="Theme.AppCompat.Light">
        <item name="android:background">@android:color/white</item>
    </style>-->
</resources>


3. menu_main.xml

<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:com.example.kamalvaid.actionbardemo="http://schemas.android.com/apk/res-auto"
>

    <item android:id="@+id/sym_action_email"
        android:icon="@android:drawable/sym_action_email"
        android:title="action search"
        com.example.kamalvaid.actionbardemo:showAsAction="ifRoom"  />
    <!-- Settings, should always be in the overflow -->
    <item android:id="@+id/action_settings"
        android:title="@string/action_settings"
        com.example.kamalvaid.actionbardemo:showAsAction="ifRoom" />
</menu>


4. activity_main.xml

<RelativeLayout 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" android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".MainActivity">

    <TextView android:text="@string/hello_world" android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

</RelativeLayout>


output : 











References : https://developer.android.com/training/basics/actionbar/setting-up.html



No comments:

Post a Comment