How to add simple menu in android?
Now lets Create a simple menu item in android.
There are 3 types of menu in android.
1.Options menu
2.Context menu
3.Popup menu
First we'll discuss about options menu
1.MainActivity.java
1.Options menu
2.Context menu
3.Popup menu
First we'll discuss about options menu
1.MainActivity.java
package com.sri.menus;
import android.os.Bundle;
import android.app.Activity;
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) {
// TODO Auto-generated method stub
switch (item.getItemId()) {
case R.id.m1:
Toast.makeText(getApplicationContext(), "menu 1",
Toast.LENGTH_SHORT).show();
break;
case R.id.m2:
Toast.makeText(getApplicationContext(), "menu 2",
Toast.LENGTH_SHORT).show();
default:
break;
}
return super.onOptionsItemSelected(item);
}
}
2.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" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Displaying Menu" />
</RelativeLayout>
3. Check in res/menu folder the main.xml
in that
<menu xmlns:android="http://schemas.android.com/apk/res/android" >
<item
android:id="@+id/action_settings"
android:orderInCategory="100"
android:showAsAction="never"
android:title="@string/action_settings"/>
<item
android:id="@+id/m1"
android:showAsAction="ifRoom"
android:title="menu 1"/>
<item
android:id="@+id/m2"
android:showAsAction="ifRoom"
android:title="menu 2"/>
</menu>
4. In main.xml, the android:showAsAction="ifRoom" is written to show it on the action bar and have the more priority.
android:showAsAction="never" is used to hide in the menu and show's on more button.
5.That's it now run it.
No comments:
Post a Comment