在运行时更改导航抽屉项目

时间:2015-09-18 10:06:24

标签: android android-layout navigation-drawer

案例如下:我有两种类型的用户,type1和type2。两者都必须登录才能进入具有导航抽屉的主要活动。导航抽屉中的项目取决于用户的类型。在知道用户类型后,如何在运行时更改导航抽屉的项目。

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 个答案:

答案 0 :(得分:5)

我找到了更简单的方法来更改导航视图(使用子菜单和菜单)。您可以在运行时使用2行代码重新充气NavigationView。在此示例中,当用户成功登录时,我会使用new_navigation_drawer_items.xml重新充气

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

当用户退出时,只需使用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.