Tag Archives: android

Android menuItem invisible set to visible

Let’s say we have 2 menu items in a menu, one of which is visible and the other not.

So in /res/menu/main_menu.xml we have:

<menu xmlns:android="http://schemas.android.com/apk/res/android" >

    <item
        android:id="@+id/menu_1"
        android:title="@string/menu_1"
        android:visible="true"
        />
    <item
        android:id="@+id/menu_2"
        android:title="@string/menu_2"
        android:visible="false"
        />

</menu>

This is all good and we will see the first item but not the second.
What happens if at some moment we need to make the second item visible. We naturally try

this.findViewById(R.id.menu_2).setVisibility(View.VISIBLE);

which will fail due to null pointer. However

this.findViewById(R.id.menu_1).setVisibility(View.GONE);

Will work.
This is because menuItem 2 has never been generated as a view and thus never found.
Note that menu items can be visible or invisible(gone) no middle option as with the views.

So to set a menuitem visible we need:
1) save the menu instance from “onCreateOptionsMenu” callback:

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

2) use this instance to find the Menu Item and set it visible

currentMenu.findItem(R.id.menu_2).setVisible(true);

Android menu item set onClick method from xml

There is a simple and easy way to set the callback method for a view from the xml describing the view.

We simply need to add to our view:

android:onClick="doTheClick"

And then in the code implement the “doTheClick” method.

public void doTheClick(View v) {    	
		//do smth here
	}

To do this for a menuItem you just need to change the “doTheClick” so it accepts MenuItem argument.

public void doTheClick(MenuItem mi) {    	
		//do smth here
	}

activity full screen mode – remove title and status bar

Status bar comes from the android system.

Title bar comes from the application.

you can remove either of them either by editing the manifest of the activity.

Remove Title Bar

in Manifest: in the activity element add: android: theme=”@android:style/Theme.NoTitleBar”

in Activity: code in OnCreate before setting the layout add: requestWindowFeature(Window.FEATURE_NO_TITLE);

Remove Title Bar and Status Bar

in Manifest: in the activity element add: android: theme=”@android:style/Theme.NoTitleBar.Fullscreen”

in Activity: code in OnCreate  add: this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);