Changing navigation drawer items at runtime

北城余情 提交于 2020-01-15 11:05:00

问题


The case is the following: I have two types of users, type1 and type2. Both have to login in order to go to the main activity which has a Navigation Drawer. The items in the navigation drawer depends on the type of the user. How can I change the items of the navigation drawer at runtime after I know the user type.

MainActivity.java

package com.example.motassem.navdrawer;

import android.content.SharedPreferences;
import android.content.res.Configuration;
import android.preference.PreferenceManager;
import android.support.design.widget.NavigationView;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;

public class MainActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener {

    private static final String SELECTED_ITEM_ID = "selected_item_id";
    private static final String FIRST_TIME = "first_time";
    private Toolbar mToolbar;
    private NavigationView mDrawer;
    private DrawerLayout mDrawerLayout;
    private ActionBarDrawerToggle mDrawerToggle;
    private int mSelectedID;
    private boolean mUserSawDrawer = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        //mMainLayout = (LinearLayout) findViewById(R.id.main_content);

        mToolbar = (Toolbar) findViewById(R.id.app_bar);
        setSupportActionBar(mToolbar);

        mDrawer = (NavigationView) findViewById(R.id.main_drawer);
        mDrawer.setNavigationItemSelectedListener(this);
        mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);

        mDrawerToggle = new ActionBarDrawerToggle(this,
                mDrawerLayout, mToolbar,
                R.string.drawer_open,
                R.string.drawer_close);
        mDrawerLayout.setDrawerListener(mDrawerToggle);
        mDrawerToggle.syncState();

        if (!didUserSeeDrawer()) {
            showDrawer();
            markDrawerSeen();
        } else {
            hideDrawer();
        }

        mSelectedID = savedInstanceState == null ? R.id.navigation_item_1 : savedInstanceState.getInt(SELECTED_ITEM_ID);
        if (mSelectedID == R.id.navigation_item_1) {
            // This is the first time i.e. NO FRAGMENTS WERE ADDED BEFORE..?

        }
        navigate(mSelectedID);

    }

    private boolean didUserSeeDrawer() {
        SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
        return sharedPreferences.getBoolean(FIRST_TIME, false);
    }

    private void markDrawerSeen() {
        SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
        mUserSawDrawer = true;
        sharedPreferences.edit().putBoolean(FIRST_TIME, mUserSawDrawer).apply();
    }

    private void hideDrawer() {
        mDrawerLayout.closeDrawer(GravityCompat.START);
    }

    private void showDrawer() {
        mDrawerLayout.openDrawer(GravityCompat.START);
    }

    private void navigate(int mSelectedID) {

        switch (mSelectedID) {
            // Edit here to navigate..
            case R.id.navigation_item_1: // History was pressed.
                mDrawerLayout.closeDrawer(GravityCompat.START);
                getSupportFragmentManager().beginTransaction().replace(R.id.main_content, new FragmentTotal()).commit();
                break;
            case R.id.navigation_item_2: // Stores was pressed.
                mDrawerLayout.closeDrawer(GravityCompat.START);
                getSupportFragmentManager().beginTransaction().replace(R.id.main_content, new FragmentTransactionComplete()).commit();
                break;
            case R.id.navigation_item_3: // Settings was pressed.
                mDrawerLayout.closeDrawer(GravityCompat.START);
                getSupportFragmentManager().beginTransaction().replace(R.id.main_content, new FragmentUpdateCard()).commit();
                break;
        }
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        mDrawerToggle.onConfigurationChanged(newConfig);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, 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();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    @Override
    public boolean onNavigationItemSelected(MenuItem menuItem) {
        menuItem.setChecked(true);
        mSelectedID = menuItem.getItemId();
        navigate(mSelectedID);
        return true;
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putInt(SELECTED_ITEM_ID, mSelectedID);
    }

    @Override
    public void onBackPressed() {
        if (mDrawerLayout.isDrawerOpen(GravityCompat.START)) {
            mDrawerLayout.closeDrawer(GravityCompat.START);
        } else {
            super.onBackPressed();
        }
    }
}

activity_main.xml

<android.support.v4.widget.DrawerLayout 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"
    android:id="@+id/drawer_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.example.motassem.navdrawer.MainActivity">

    <LinearLayout
        android:id="@+id/main_content"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical">

        <android.support.v7.widget.Toolbar
            android:id="@+id/app_bar"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:background="@color/colorPrimary"
            android:minHeight="?attr/actionBarSize"
            app:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar">


        </android.support.v7.widget.Toolbar>


    </LinearLayout>

    <android.support.design.widget.NavigationView
        android:id="@+id/main_drawer"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:layout_gravity="start"
        app:headerLayout="@layout/drawer_header"
        app:itemIconTint="@color/colorAccent"
        app:itemTextColor="@color/colorTextSecondary"
        app:menu="@menu/menu_drawer">

    </android.support.design.widget.NavigationView>

</android.support.v4.widget.DrawerLayout>

menu_item.xml

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
    <item
        android:id="@+id/navigation_item_1"
        android:icon="@drawable/ic_history"
        android:title="@string/navigation_item_1" />
    <item
        android:id="@+id/navigation_item_2"
        android:icon="@drawable/ic_cart"
        android:title="@string/navigation_item_2" />
    <item
        android:id="@+id/navigation_item_3"
        android:icon="@drawable/ic_card"
        android:title="@string/navigation_item_3" />
</menu>

回答1:


I found easier way to change navigation view ( work with both submenu and menu). You can re-inflate NavigationViewat runtime with 2 lines of code. In this example i re-inflate with new_navigation_drawer_items.xml when user successfully logged-in

navigationView.getMenu().clear(); //clear old inflated items.
navigationView.inflateMenu(R.menu.logged_in_navigation_drawer_items); //inflate new items.

When user log out just re-inflate again with logged_out_navigation_drawer_items.xml

navigationView.getMenu().clear(); //clear old inflated items.
navigationView.inflateMenu(R.menu.logged_out_navigation_drawer_items); //inflate new items.


来源:https://stackoverflow.com/questions/32649333/changing-navigation-drawer-items-at-runtime

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