Enable an ActionBar Button each time navigation within tabs occurs.

ε祈祈猫儿з 提交于 2019-12-13 13:47:12

问题


I have a main activity in which I designate tabs using three fragments. I have a button on the ActionBar which navigates to a different fragment say "Info about the app" Once user navigates to this particular fragment (Info) I disable it so that it is not called again and again. Then on the back key in the main activity I re-enable it. So far so good. But I am not able to re-enable it for one scenario: Say if user navigates to the info fragment and does not press back, but however if he navigates to a different tab, the info button is still disabled because back-press has not been called. I tried a lot of things in onStart() and onResume() of fragments but I am not able to reference the menuItem in any of those as I get a null pointer.

Code Reference: (MainActivity while calling the info fragment from onOptionsSelected):

public boolean onOptionsItemSelected(MenuItem item) {

        mMenuItem = item; 
        switch (item.getItemId()) {
        case R.id.info:
            Tab d = getActionBar().getSelectedTab();

            System.out.println(""+d.getText().toString()); 
            FragmentManager fragmentManager = getFragmentManager();  
            FragmentTransaction fragmentTransaction = fragmentManager  
                    .beginTransaction();  

            String a = d.getText().toString(); 
            if(a.equalsIgnoreCase("Reminders")){ 
                FragmentContact fragmentcontact = new FragmentContact(); 
                fragmentTransaction.replace(R.id.realtabcontent, fragmentcontact);  
                mMenuItem.setEnabled(false); 
                //mMenuItem.setIcon(R.drawable.btn_age_01); 
            }
            else if(a.equalsIgnoreCase("Notifications")){
                FragmentContact fragmentcontact = new FragmentContact();
                fragmentTransaction.replace(R.id.realtabcontent2, fragmentcontact);  
                mMenuItem.setEnabled(false); 

            }
            else if(a.equalsIgnoreCase("Contacts")){
                FragmentContact fragmentcontact = new FragmentContact(); 
                fragmentTransaction.replace(R.id.realtabcontent3, fragmentcontact); 
                mMenuItem.setEnabled(false); 

            }
            fragmentTransaction.addToBackStack(null);
            fragmentTransaction.commit();  



            break;

on Back key(Main Activity):

@Override
    public void onBackPressed() {
        mMenuItem.setEnabled(true);
        super.onBackPressed();
    }

回答1:


The solution was very simple, to set an options menu for individual "Fragments" use:

setHasOptionsMenu(true);

Cheers!!



来源:https://stackoverflow.com/questions/20393016/enable-an-actionbar-button-each-time-navigation-within-tabs-occurs

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!