Lechat Noir Lechat Noir - 2 months ago 18
Android Question

Logout in action bar

For my application I used a bouton to logout, but now I would like to use the action bar (When user click on logout icon he goes to homepage) and I can't make them live together.

(I'm french, its hard to code because all tuto are in english. So please be patient with me).

Thank you very much.

My button code was :

btn_logout.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
sessionManager.logout();
Intent intent = new Intent(getApplicationContext(), MainActivity.class);
startActivity(intent);
finish();
}
});


My code where I would like to add icon logout :

@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();

if (id == R.id.action_logout) {
return true;
}

return super.onOptionsItemSelected(item);
}


My XML :

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">

<item
android:id="@+id/action_logout"
android:icon="@android:drawable/ic_lock_power_off"
android:title="@string/logout"
app:showAsAction="ifRoom" />

</menu>

Answer

You need to do something when the user taps the menu item.

if (id == R.id.action_logout) {
    logout();
    return true;
}

Move your logout code to a method so you can call it from any place:

private void logout() {
    sessionManager.logout();
    startActivity(new Intent(this, MainActivity.class));
    finish();
}
Comments