Menu is null when activity gets recreated - android

I have inflated the action bar menu in the base activity and modifying the action bar items in my base activity. But When i change the orientation, menu is always null and thats why it doesn't update my action bar items. Why it null?
Here is my tried code:
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.base, menu);
mMenu = menu;
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// switch (item.getItemId()) {
if (item.getItemId() == R.id.action_refresh) {
refreshNewsData();
return true;
}
if (item.getItemId() == R.id.action_share) {
sharenewsData();
return true;
}
if (item.getItemId() == R.id.action_favorite) {
addFavorites();
return true;
}
return super.onOptionsItemSelected(item);
}
I have written this code in base activity.
protected void showIcons(int id) {
if (mMenu != null) {
MenuItem item = mMenu.findItem(id);
item.setVisible(true);
}
}
protected void hideIcons(int id) {
if (mMenu != null) {
MenuItem item = mMenu.findItem(id);
item.setVisible(false);
}
I'm using these methods to update the action bar menu items

You cannot update ActionBar Menu items directly. Whenever you want to update menu items, make a call to invalidateOptionsMenu() this'll redraw the action bar menus and will make a call to onPrepareOptionsMenu(). You'll have to take care of the menu items you want to show / hide inside onPrepareOptionsMenu().

Related

How to switch between two menu icons

I have menu items that are inflated on my toolbar.When one menu item icon is clicked i would like to switch that with another icon and vice versa. I'm doing this so that i can switch between listview and gridview.
What i have tried is to recreate the menu again with a different menu.xml. But the app crashes when i call onCreateOptionsMenu(menu) from onOptionsItemSelected(MenuItem item){}.
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_grid) {
listView.setVisibility(View.INVISIBLE);
gv.setVisibility(View.VISIBLE);
//i try to recreate menu again
onCreateOptionsMenu(menu)
}
if (id == R.id.action_list) {
listView.setVisibility(View.VISIBLE);
gv.setVisibility(View.INVISIBLE);
//i try to recreate menu again
onCreateOptionsMenu(menu)
}
return super.onOptionsItemSelected(item);
}
Is there a way to achieve this?
Menu optionsMenu;
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.refresh_menu, menu);
optionsMenu = menu;
}
**Somewhere in code**
final MenuItem refreshItem = optionsMenu
.findItem({ID OF MENU Item});
refreshItem.setIcon({New Icon Resource});
You don't need to recreate menu everytime, Just handle MenuItems
#Override
public boolean onOptionsItemSelected(MenuItem item) {
String title = item.getTitle().toString();
switch (title) {
case TITLE_GRIDVIEW:
item.setTitle(TITLE_LISTVIEW);
item.setIcon(R.drawable.listview_icon);
//switch to gridview
return true;
case TITLE_LISTVIEW:
item.setTitle(TITLE_GRIDVIEW);
item.setIcon(R.drawable.gridview_icon);
//switch to listview
return true;
}
return false;
}
It works based on the binded title to your item, In this way you just need one item in your menu to switch between listview and gridview and this items acts like a toggle button.
Instead of trying to re-create the menu, just change the icon and maintain state with a boolean flag:
boolean flag = true;
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_grid_list_toggle) {
if (boolean) {
// Show grid view
item.setIcon(R.drawable.ic_grid);
listView.setVisibility(View.INVISIBLE);
gv.setVisibility(View.VISIBLE);
} else {
// Show list view
item.setIcon(R.drawable.ic_list);
listView.setVisibility(View.VISIBLE);
gv.setVisibility(View.INVISIBLE);
}
flag = !flag; // toggle value on every click
}
return super.onOptionsItemSelected(item);
}

Action bar items not working with Drawer Android

My Action bar items were working fine until I added a menu drawer, now when the activity is first displayed, the switch button on the menu doesn't work and as soon as the drawer opens it starts working absolutely fine. Although I have not called it in my onDrawerOpened method.
// ----------For Options Menu-------------------
#Override
public boolean onCreateOptionsMenu(Menu menu) {
try {
super.onCreateOptionsMenu(menu);
menu.clear();
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main_screen_menu, menu);
menuitem1 = menu.findItem(R.id.menu_item1);
menuitem2 = menu.findItem(R.id.menu_item2);
final Switch getView = (Switch) menuitem2.getActionView();
getView.setChecked(false);
getView.setOnCheckedChangeListener(new OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton arg0,
boolean isSelected) {
if (isSelected) {
method1();
} else {
method2();
}
}
});
} catch (Exception e) {
e.printStackTrace();
Log.e("OnCreateOptionsMenu", "exception", e);
}
mOptionsMenu = menu;
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
super.onOptionsItemSelected(item);
// toggle nav drawer on selecting action bar app icon/title
if (mDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
// Handle action bar actions click
switch (item.getItemId()) {
case R.id.menu_item1: {
return true;
}
case R.id.menu_item2: {
return true;
}
default:
return super.onOptionsItemSelected(item);
}
}
Once I open and close the Drawer than the switch is working perfectly!
Can anyone please help?
Thanks in advance.
You're supposed to call super.onCreateOptionsMenu(menu) after having inflated the menu (as shown in the docs : http://developer.android.com/guide/topics/ui/actionbar.html)
I would change your code to :
// ----------For Options Menu-------------------
#Override
public boolean onCreateOptionsMenu(Menu menu) {
try {
menu.clear();
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main_screen_menu, menu);
(...)
return super.onCreateOptionsMenu(menu);
}
(Not totally sure that it could fix your issue, but it's worth the try)

Android back option in action bar

When I created an activity it automatically added a back to main activity option in the action bar. It looks like those are the functions that do it:
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.app_settings, 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.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
Is there a way to make it go back using finish()? Right now it looks like it resets some values that are saved and I want to keep them. When I tried working with finish() it didn't do it but i'm not sure how to use it in the action bar.
This is simpler and it works perfect:
public class BackButtonExample extends Activity {
#SuppressLint("NewApi")
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.duahs);
ActionBar bar = getActionBar();
bar.setBackgroundDrawable(new ColorDrawable(Color.parseColor("#0B4C5F")));
bar.setDisplayHomeAsUpEnabled(true);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
this.finish();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
}
Try this
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if(item.getItemId()==android.R.id.home {
finish();
return true; }
else{
return super.onOptionsItemSelected(item);
}
}

How to prevent ActionBar items get hidden when Navigation Drawer opens?

I have implemented Navigation Drawer with ActionBar which has only one item which opens the navigation drawer. So both the Home and menu item buttons open the drawer. And all works fine with no crashes.
But when I click on the ActionBar Home button or menu item, the Navigation drawer opens and menu item becomes invisible.
How can I prevent this? I want it be always visible, regardless if drawer is open or closed.
I tried multiple solutions already. For example, in the drawer class, method setHasOptionsMenu(true); is called in onCreate. Then I set menu item to be present always.
Then in the main Activity, I tried to capture the menu item during the creation
#Override
public boolean onPrepareOptionsMenu(Menu menu) {
try {
MenuItem item = menu.getItem(0);
if (item != null) {
item.setVisible(true);
}
} catch (Exception e) {
Log.e(TAG, "Error: " + e.getLocalizedMessage());
}
return super.onPrepareOptionsMenu(menu);
}
but when drawer appears, the menu object return with 0 items.
I am out of ideas.
EDIT
#Override
public boolean onCreateOptionsMenu(Menu menu) {
if (!mNavigationDrawerFragment.isDrawerOpen())
getMenuInflater().inflate(R.menu.main, menu);
restoreActionBar();
return true;
}
return super.onCreateOptionsMenu(menu);
}
public void restoreActionBar() {
ActionBar actionBar = getActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD);
actionBar.setDisplayShowTitleEnabled(false);
actionBar.setDisplayShowHomeEnabled(true);
actionBar.setDisplayHomeAsUpEnabled(false);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (item != null && id == android.R.id.home) {
if (mNavigationDrawerFragment.isDrawerOpen(Gravity.RIGHT)) {
mNavigationDrawerFragment.closeDrawer(Gravity.RIGHT);
} else {
mNavigationDrawerFragment.openDrawer(Gravity.RIGHT);
}
return true;
}
return super.onOptionsItemSelected(item);
}
This is RIGHT-SIDE Navigation drawer.
this is your problem
#Override
public boolean onCreateOptionsMenu(Menu menu) {
if (!mNavigationDrawerFragment.isDrawerOpen())
getMenuInflater().inflate(R.menu.main, menu);
restoreActionBar();
return true;
}
return super.onCreateOptionsMenu(menu);
}
you dont have a menu when the drawer opens, remove that if statement

Android Quick Contextual bar on textview

In Android if the textview is selected then a word gets selected and a contextual action bar comes at the top...i want to modify that CAB and make it look like a quick action bar...keeping the text selection feature intact...please help me...
you can select textview or anything like only in simple layout CAB appear in the top and there was some method onActionItemClicke that you want to click an item and then you modify your action in CAB default behavior................................
public class MainActivity extends Activity {
protected Object mActionMode;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
View view = findViewById(R.id.lay);
view.setOnLongClickListener(new View.OnLongClickListener() {
// Called when the user long-clicks on someView
public boolean onLongClick(View view) {
if (mActionMode != null) {
return false;
}
mActionMode = MainActivity.this.startActionMode(mActionModeCallback);
view.setSelected(true);
return true;
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
Toast.makeText(this, "Just a test", Toast.LENGTH_SHORT).show();
return true;
}
private ActionMode.Callback mActionModeCallback = new ActionMode.Callback() {
// Called when the action mode is created; startActionMode() was called
public boolean onCreateActionMode(ActionMode mode, Menu menu) {
// Inflate a menu resource providing context menu items
MenuInflater inflater = mode.getMenuInflater();
// Assumes that you have "contexual.xml" menu resources
inflater.inflate(R.menu.cab, menu);
return true;
}
// Called each time the action mode is shown. Always called after
// onCreateActionMode, but
// may be called multiple times if the mode is invalidated.
public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
return false; // Return false if nothing is done
}
// Called when the user selects a contextual menu item
public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
switch (item.getItemId()) {
case R.id.toast:
Toast.makeText(MainActivity.this, "Selected menu",
Toast.LENGTH_LONG).show();
mode.finish(); // Action picked, so close the CAB
return true;
case R.id.shan:
Toast.makeText(MainActivity.this, "Selected shani",
Toast.LENGTH_LONG).show();
mode.finish(); // Action picked, so close the CAB
return true;
default:
return false;
}
}
// Called when the user exits the action mode
public void onDestroyActionMode(ActionMode mode) {
mActionMode = null;
}
};
}
and in menu xml file create menu that you would like to appear in top CAB
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android" >
<item
android:id="#+id/toast"
android:title="Toast">
</item>
<item
android:id="#+id/shan"
android:title="shani">
</item>
</menu>

Categories

Resources