Hide a Navigation Drawer Menu Item - Android

后端 未结 8 668
春和景丽
春和景丽 2021-01-30 06:31

I have a navigation drawer. When an event is called, I want to hide one of my navigation menu item for user. How can I do that?

protected void onCreate(Bundle sa         


        
8条回答
  •  南笙
    南笙 (楼主)
    2021-01-30 07:11

        //hide logout menu item when the user is not loggrd in
        //Checking the condition whether the user is logged in or not
    
        if (!SharedPrefManager.getmInstance(this).isLoggedIn()){
            Menu nav_Menu = navigationView.getMenu();
        nav_Menu.findItem(R.id.nav_logout).setVisible(false);
        }
    
    
     //SharedPrefManager .java class where we define the isLoggedIn Method()
    
    import android.content.Context;
    import android.content.SharedPreferences;
    
    import com.motortrade.motortrade.t_Model.User;
    
    public class SharedPrefManager {
    
    private static final String SHARED_PREF_NAME = "my_shared_pref";
    
    private  static SharedPrefManager mInstance;
    private Context mCtx;
    
    private SharedPrefManager(Context mCtx){
        this.mCtx = mCtx;
    }
    
    public static synchronized SharedPrefManager getmInstance(Context mCtx){
        if (mInstance == null){
            mInstance = new SharedPrefManager(mCtx);
        }
        return mInstance;
    }
    
    public boolean isLoggedIn(){
        SharedPreferences preferences = mCtx.getSharedPreferences(SHARED_PREF_NAME, Context.MODE_PRIVATE);
    
       return preferences.getInt("user_id", -1) != -1;
    }
    

提交回复
热议问题