Tuesday, 19 May 2015

Android how to hide a menu item in the actionbar

Here I am going to explain how to hide a menu item in ActionBar


1). Open res ⇒ menu⇒ main.xml and add below items.

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

    <item
        android:id="@+id/Import"
        android:icon="@android:drawable/ic_menu_save"
        android:showAsAction="ifRoom"
        android:title="Import"/>
    <item
        android:id="@+id/action_add"
        android:icon="@android:drawable/ic_input_add"
        android:showAsAction="ifRoom"
        android:title="Add"/>

</menu>

2)Activity Before Hiding a menu item.

package com.example.hide_menu;
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;

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 true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {

int id = item.getItemId();
if (id == R.id.Import) 
{
return true;
}
return super.onOptionsItemSelected(item);
}
}
                     

2)Activity After Hiding a menu item.

ackage com.example.hide_menu;
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;

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);

  MenuItem Import = menu.findItem(R.id.Import);
Import.setVisible(false);
return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {

int id = item.getItemId();
if (id == R.id.Import) 
{
return true;
}
return super.onOptionsItemSelected(item);
}
}


Happy Coding :)