Monday, 24 June 2013

ActionBar Menu

ScreenShots:



strings.xml:
<?xml version="1.0" encoding="utf-8"?>
<resources>

    <string name="app_name">ActionBar</string>
    <string name="action_settings">Settings</string>
    <string name="hello_world">Hello world!</string>
    <string name="updateItemText">Update</string>
    <string name="DeleteItemText">Delete</string>

</resources>

Note: Create following main.xml file under menu folder.
main.xml:
<menu xmlns:android="http://schemas.android.com/apk/res/android" >

    <item
        android:id="@+id/updateitem"
        android:orderInCategory="100"
        android:showAsAction="ifRoom|withText"
        android:title="@string/updateItemText"/>
    <item
        android:id="@+id/delitem"
        android:orderInCategory="100"
        android:showAsAction="ifRoom|withText"
        android:title="@string/DeleteItemText"/>

</menu>

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: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" >

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

</RelativeLayout>


MainActivity.java:
package com.ram.actionbar;

import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Toast;

public class MainActivity extends Activity {

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

}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return super.onCreateOptionsMenu(menu);
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.delitem:
Toast.makeText(getApplicationContext(), "Delete Selected",
Toast.LENGTH_SHORT).show();
break;

case R.id.updateitem:
Toast.makeText(getApplicationContext(), "Update Selected",
Toast.LENGTH_SHORT).show();
break;
}
return super.onOptionsItemSelected(item);
}
}