Wie kann ich Menüpunkte dynamisch erstellen?

Ich erstelle eine Android-Anwendung und versuche, ein Benutzerverwaltungssystem zu erstellen, in dem sich Benutzer anmelden, abmelden usw. Ich möchte ein Anmeldemenüelement anzeigen, wenn der Benutzer abgemeldet ist, und eine Schaltfläche zum Abmelden, wenn der Benutzer angemeldet ist Wie kann ich das dynamisch machen?

Dies ist jetzt die Layoutdatei:

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
  <item android:id="@+id/add" android:title="Add" android:icon="@drawable/ic_menu_add"/>
  <item android:id="@+id/list" android:title="List" android:icon="@drawable/ic_menu_list"/>
  <item android:id="@+id/refresh" android:title="Refresh" android:icon="@drawable/ic_menu_refresh"/>
  <item android:id="@+id/login" android:title="Login" android:icon="@drawable/ic_menu_login"/>
</menu>

Dies ist momentan mein Java:

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    new MenuInflater(this).inflate(R.menu.activity_main, menu);
    return(super.onCreateOptionsMenu(menu));
}

@Override
public boolean onOptionsItemSelected(MenuItem item) 
{
    System.out.println(item.getItemId()==R.id.add);
    if (item.getItemId()==R.id.add)
    {
        //Cannot add spot unless we have obtained the users current location. 
        if((currentLat != 0) && (currentLng != 0))
        {

            System.out.println("loggedin? : "  + auth.isLoggedIn());
            if(!auth.isLoggedIn())
            {
                Toast.makeText(MainActivity.this, "You must be logged in to add a new spot",
                        Toast.LENGTH_LONG).show();
            }
            else
            {


                Intent addIntent = new Intent(MainActivity.this, AddSpot.class);
                Bundle b = new Bundle();
                b.putDouble("currentLat", currentLat);
                b.putDouble("currentLng", currentLng);
                addIntent.putExtras(b);
                startActivity(addIntent);
                return(true);
            }
        }
    }   
    else if(item.getItemId()==R.id.list)
    {
        //Pointless showing them a blank screen if nothing is retrieved from the server
        if(list != null)
        {
            Intent listIntent = new Intent(MainActivity.this, ListLocations.class);
            listIntent.putExtra("list", list);
            startActivity(listIntent);
            return(true);
        }
    }

    if(item.getItemId()==R.id.refresh)
    {
        finish();
        startActivity(getIntent());
        return(true);       
    }

    if(item.getItemId()==R.id.login)
    {
        Intent loginIntent = new Intent(MainActivity.this, LoginActivity.class);
        startActivity(loginIntent);
        return(true);   
    }

    return(super.onOptionsItemSelected(item));
}

Antworten auf die Frage(5)

Ihre Antwort auf die Frage