Невозможно скрыть меню переполнения Android при отображении определенных фрагментов

Что я достиг

Я работаю над приложением Android, которое использует блок навигации, прикрепленный к моей основной функции, чтобы отображать определенные макеты при выборе пользователем элемента навигации. Я также создал файл ресурсов меню для меню переполнения, которое должно появиться в панели приложений.

Чего я не могу достичь

Однако созданное мной меню переполнения отображается в панели приложений независимо от выбранного пользователем элемента панели навигации. Мне нужно, если возможно, скрыть это меню переполнения из панели приложения, когда отображаются макеты календаря / настройки. (Код найден ниже)

Что я пытался сделать

Я пытался играть с setHasOptionsMenu() метод и установка его в false в моем файле календаря / настроек Java.

Код приложения

Основная деятельность

package com.example.lukeb.calendar;

import android.app.Activity;
import android.app.Fragment;
import android.content.Intent;
import android.os.Build;
import android.support.annotation.NonNull;
import android.support.design.widget.NavigationView;
import android.support.v4.app.FragmentActivity;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBar;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.text.Html;
import android.transition.Visibility;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.RelativeLayout;


public class MainActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener{

    // Declare needed objects as global variables for access throughout the program

    RelativeLayout lay1;
    RelativeLayout lay2;
    RelativeLayout lay3;
    DrawerLayout drawerLayout;
    ActionBar actionBar;
    Toolbar toolbar;

    // Default method called automatically when activity is created

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);         // Set the content of this activity to the activity_main XML file
        navigate();                                     // Once finished with this, call the navigate function found below
    }

    // Method created to prep navigation drawer

    public void navigate(){                                 // Method called in onCreate method

        // If device is running Lollipop or above, run the following...
        if(Build.VERSION.SDK_INT >= 21) {
            toolbar = (Toolbar) findViewById(R.id.toolbar3);            // Set variable "toolbar" to item named "toolbar3" in XML file
            setSupportActionBar(toolbar);                               // Designate the item set to "toolbar" as the activity's actionBar
            actionBar = getSupportActionBar();                          // Set variable "actionBar" to whatever the activity's actionBar is. This is necessary for checking it later.
            lay1 = (RelativeLayout) findViewById(R.id.one);             // Initialize variables "lay1", "lay2", and "lay3" - that were originally declared above - to their respective XML items.
            lay2 = (RelativeLayout) findViewById(R.id.two);             //    < __________________________|           |
            lay3 = (RelativeLayout) findViewById(R.id.three);           //    < ______________________________________|


            drawerLayout = (DrawerLayout) findViewById(R.id.dLayout);   // Initialize variable "drawerLayout" to XML item "dLayout".
            if (actionBar != null) {                                    // Check if the activity's actionBar has been set (not equal to null)
                actionBar.setDisplayHomeAsUpEnabled(true);              // Enables the actionBar's back button
                ActionBarDrawerToggle mDrawerToggle = new ActionBarDrawerToggle(this, drawerLayout, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close) {       // Create a new AppDrawer toggle. Refer to android documentation for more info on parameters. Also defines its own constructor after the class object.
                    public void onDrawerClosed(View view) {  // Method called when drawer is closed
                        supportInvalidateOptionsMenu();      // Declare that the options menu has changed, so should be recreated. It will be recreated when needed.

                    }

                    public void onDrawerOpened(View drawerView){    // Method called when drawer is opened
                        supportInvalidateOptionsMenu();             // Once again, declare that the options menu has changed, so should be recreated. It will be recreated when needed.

                    }
                };
                mDrawerToggle.setDrawerIndicatorEnabled(true);      // Enable drawer indicator on the "mDrawerToggle" which, in turn, enables the animated glyph on the activity's actionBar
                drawerLayout.setDrawerListener(mDrawerToggle);      // Set the appDrawer's actionListener to our newly created "mDrawerToggle" object
                mDrawerToggle.syncState();                          // Sync the appDrawer's indicator with the current state of the DrawerLayout
                setListener();                                      // Call the setListener method below

            }
        }
    }

    // Sets the item listener
    public void setListener(){
        NavigationView nView = (NavigationView) findViewById(R.id.nav_view);    // Declare a variable named "nView" and initialize it to the "nav_view" XML item.
        nView.setNavigationItemSelectedListener(this);                          // Set the listener called for a selected navDrawer item to one found below
    }


    // A method that is called when a navDrawer item is selected
    @Override
    public boolean onNavigationItemSelected(@NonNull MenuItem item) {
        switch(item.getItemId()){                                               // Check which item was selected by returning its ID
            case R.id.action_feed:                                              // If the item selected's ID is "R.id.action_feed"
                actionBar.setTitle("Your Feed");                                // Set actionBar title to correct page title
                lay3.setVisibility(View.GONE);                                  // Hide layout3 from the "stack of layouts"
                lay2.setVisibility(View.GONE);                                  // Hide layout2 from the "stack of layouts"
                lay1.setVisibility(View.VISIBLE);                               // Show only the selected item on screen

                break;                                                          // Leave or "break" from the loop

            case R.id.action_calendar:                                          // If the item selected's ID is "R.id.action_calendar"
                actionBar.setTitle("Calendar");                                 // Set actionBar title to correct page title
                lay1.setVisibility(View.GONE);                                  // Hide layout1 from the "stack of layouts"
                lay3.setVisibility(View.GONE);                                  // Hide layout3 from the "stack of layouts"
                lay2.setVisibility(View.VISIBLE);                               // Show only the selected item on screen
                break;                                                          // Leave or "break" from the loop

            case R.id.action_settings:                                          // If the item selected's ID is "R.id.action_settings"
                actionBar.setTitle("Settings");                                 // Set actionBar title to correct page title
                lay1.setVisibility(View.GONE);                                  // Hide layout1 from the "stack of layouts"
                lay2.setVisibility(View.GONE);                                  // Hide layout3 from the "stack of layouts"
                lay3.setVisibility(View.VISIBLE);                               // Show only the selected item on screen
                break;                                                          // Leave or "break" from the loop

        }
        drawerLayout.closeDrawer(GravityCompat.START);                          // Regardless of selection, close drawer when loaded
        return true;                                                            // Return true if navDrawer item was indeed selected
    }

    public boolean newEvent(MenuItem item){
        Intent i = new Intent(MainActivity.this, NewEvent.class);
        startActivity(i);
        return true;
    }
}

FragOne

package com.example.lukeb.calendar;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.View;
import android.view.ViewGroup;

public class FragOne extends Fragment {

    @Override
    public void onCreate(Bundle savedInstanceState){
        super.onCreate(savedInstanceState);
        setHasOptionsMenu(true);
    }

    @Override
    @Nullable
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
        // Creates a new view for the fragment. Then, it sets the XML layout file as the contents of the view. Finally, a copy of this new view is returned.

        return inflater.inflate(R.layout.fragment_frag_one, container, false);
    }


    @Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater){
        //inflater = getMenuInflater();
        inflater.inflate(R.menu.overflow_one, menu);
        super.onCreateOptionsMenu(menu, inflater);
    }

}

FragTwo

package com.example.lukeb.calendar;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.View;
import android.view.ViewGroup;

public class FragTwo extends Fragment {
    @Override
    public void onCreate(Bundle savedInstanceState){
        super.onCreate(savedInstanceState);
        setHasOptionsMenu(false);
    }

    @Override
    @Nullable
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
        // Creates a new view for the fragment. Then, it sets the XML layout file as the contents of the view. Finally, a copy of this new view is returned.

        return inflater.inflate(R.layout.fragment_frag_two, container, false);
    }

    @Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        super.onCreateOptionsMenu(menu, inflater);
        menu.clear();
    }
}

1 ответ

Я знаю, что этот вопрос довольно старый, но недавно я пытался скрыть меню переполнения и подумал, что для любого, кто просматривает этот вопрос, может быть полезно посмотреть мое решение.


Вы правы, глядя на setHasOptionsMenu()Однако, я думаю, вы немного запутались в том, что это делает. Согласно документации, этот метод просто сообщает активности, что он хотел бы заполнить меню опций. Я разместил свое решение ниже в надежде, что оно поможет вам, не стесняйтесь задавать любые вопросы, если вы не понимаете.


Моим первым шагом было редактирование файла ресурсов меню, чтобы добавить все элементы в группу. Моя теперь выглядит примерно так:

<group
    android:id="@+id/main_menu_group">
    <item
        android:id="@+id/action_settings"
        android:orderInCategory="100"
        android:title="@string/action_settings"
        app:showAsAction="never" />
</group>

Затем я переопределить onPrepareOptionsMenu() метод вроде так:

@Override
public void onPrepareOptionsMenu(Menu menu) {
    Log.d("Method Calls" , "onPrepareMenuOptions");
    menu.setGroupVisible(R.id.main_menu_group, false);
    super.onPrepareOptionsMenu(menu);
}

Этот код удаляет видимость всех элементов в группе, созданной ранее, поэтому меню опций не требуется, поэтому Android не показывает его.

Этот код еще ничего не делает, так как меню опций уже создано действием, используя setHasOptionsMenu(true); во фрагментах onCreate() Метод решит это, сообщив деятельности, что он хотел бы внести некоторые изменения.

Чтобы добавить меню переполнения в другой фрагмент, вы можете повторить два последних шага внутри этого фрагмента, но изменить: menu.setGroupVisible(R.id.main_menu_group, false);

чтобы: menu.setGroupVisible(R.id.main_menu_group, true);

Другие вопросы по тегам