1. We create new project with eclipses File--> New --> Android Project it will give you default activity.
2. Go to folder /res you will saw folder name call /menu directory. Open this folder it contain main.xml file.
3. Open on it menu.xml type follow with this code, In this case each menu items I will put title and an icon. I will create 4 menu option.
- Save
- Search
- Delete
- Share
4. Copy all icon to folder /drawable-hdpi folder just go to folder of your project
Follow with this code in main.xml on folder menu
<menu 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"
tools:context="com.example.menuexaple.MainActivity" >
<item
android:id="@+id/menusave"
android:icon="@drawable/save"
android:title="Save"/>
<item
android:id="@+id/menusearch"
android:icon="@drawable/search"
android:title="Search"/>
<item
android:id="@+id/menushare"
android:icon="@drawable/share"
android:title="Share"/>
<item
android:id="@+id/menudelete"
android:icon="@drawable/removeicon"
android:title="Delete"/>
</menu>
5. Now open MainActivity.java class and follow with this code and all so we use switching case for all menu button action.
package com.example.menuexaple;
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) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.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.menusave:
Toast.makeText(getApplicationContext(), "Saved", Toast.LENGTH_SHORT)
.show();
return true;
case R.id.menusearch:
Toast.makeText(getApplicationContext(), "Searching",
Toast.LENGTH_SHORT).show();
return true;
case R.id.menushare:
Toast.makeText(getApplicationContext(), "Shared",
Toast.LENGTH_SHORT).show();
return true;
case R.id.menudelete:
Toast.makeText(getApplicationContext(), "Deleted",
Toast.LENGTH_SHORT).show();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
}
6. Run our application just right click on project folder choose Run As Android Application
Out program
1 Comments
More explain please...I like this article.
ReplyDelete