Search code examples
javaandroidandroid-actionbarvisibility

Hot to set Action Bar item visibility as soon as activity starts?


When Activity Restarts , everything works correctly, but I want to set menu item visibility when Activity starts.

private boolean userIsCompany = false;

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

    Fragment vacancyListFragment = new VacancyListFragment();
    getSupportFragmentManager().beginTransaction().replace(R.id.fragment_frame, 
                                                           vacancyListFragment).commit();


    GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
            .requestIdToken(getString(R.string.default_web_client_id))
            .requestEmail()
            .build();
    mGoogleSignInClient = GoogleSignIn.getClient(this, gso);
    final GoogleSignInAccount account = GoogleSignIn.getLastSignedInAccount(this);

If user in Firebase has child , boolean userIsCompany will become true;

    //      Check if current user is CompanyUser.
    //      If it is addVacancy button will become visible.
    assert account != null;
    companiesUidRef = mRef
            .child("Companies")
            .child(Objects.requireNonNull(account.getId()));
    companiesUidRef.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
            if (dataSnapshot.exists()) {
                userIsCompany = true;
            }
        }

        @Override
        public void onCancelled(@NonNull DatabaseError databaseError) {

        }
    });
}

Here is OncreateOptionsMenu method

@Override
public boolean onCreateOptionsMenu(final Menu menu) {
    MenuInflater inflater = getMenuInflater();
    inflater.inflate(R.menu.action_bar_menu, menu);
    MenuItem addVacancy = menu.findItem(R.id.action_add_vacancy);
    if(!userIsCompany){
        addVacancy.setVisible(false);
    }
    return true;
}

Solution

  • It looks like the variable userIsCompany won't be true before onCreateOptionsMenu is finished initialising the menu. A fix for this would be to add a call to invalidateOptionsMenu() after you set userIsCompany to true.

    This will call onCreateOptionMenu once again and it will update its visibility.