bbowesbo
bbowesbo

Reputation: 925

How to give functionality to navigation menu selection?

web dev trying (and struggling) to have a go at android application development here. I'm trying to implement a side navigation into a login system so make my UI look nicer and generally give my app a nicer feel. The problem that I am having is;

Currently on the MainActivity (dashboard/ homescreen) of the application, I have a button which basically logs out the user from the login system which I am using with the following code.

    Button logoutBtn = findViewById(R.id.btnLogout);

    logoutBtn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            session.logoutUser();
            Intent i = new Intent(MainActivity.this, LoginActivity.class);
            startActivity(i);
            finish();

        }
    });

The UI:

Logout Button

The above code works as expected, by logging out the user and re-directing them to the login/ register page. Now I've start to try and implement a side navigation I've found (https://antonioleiva.com/materialize-app/) and am struggling to work out how I can give the functionality of the above button to the navigation menu item as shown below;

enter image description here

The side navigation example I am using has the following code which basically presents a notification to show which side navigation menu item has being selected;

private void setupDrawerLayout() {
    drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);

    navigationView = (NavigationView) findViewById(R.id.navigation_view);
    navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
        @Override
        public boolean onNavigationItemSelected(MenuItem menuItem) {
            Snackbar.make(content, menuItem.getTitle() + " pressed", Snackbar.LENGTH_LONG).show();
            menuItem.setChecked(true);
            drawerLayout.closeDrawers();
            return true;
        }
    });
}

This presents the following;

enter image description here

If anyone could give me any points, hints, or help on how I can give the menu option the functionality of the logout button it would be thoroughly appreciated as once I know how to set on click listeners/ run parts of code for menu selections I can proceed to load different activities and proceed building my application.

Thanks in advance SO.

The full code for the homescreen (MainActivity.java) is below;

package com.antonioleiva.materializeyourapp;

import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.support.design.widget.NavigationView;
import android.support.design.widget.Snackbar;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity implements 
RecyclerViewAdapter.OnItemClickListener {
private SessionHandler session;
private static List<ViewModel> items = new ArrayList<>();
private DrawerLayout drawerLayout;
private View content;
private RecyclerView recyclerView;
private NavigationView navigationView;

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

    session = new SessionHandler(getApplicationContext());
    User user = session.getUserDetails();
    TextView dashboardText = findViewById(R.id.dashboardText);
    dashboardText.setText("Welcome to gluca, " + user.getFullName() + "!");

    initRecyclerView();
    initFab();
    initToolbar();
    setupDrawerLayout();

    Button logoutBtn = findViewById(R.id.btnLogout);

    logoutBtn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            session.logoutUser();
            Intent i = new Intent(MainActivity.this, LoginActivity.class);
            startActivity(i);
            finish();

        }
    });

    content = findViewById(R.id.content);

    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
        setRecyclerAdapter(recyclerView);
    }
}

@Override
public void onEnterAnimationComplete() {
    super.onEnterAnimationComplete();
    setRecyclerAdapter(recyclerView);
    recyclerView.scheduleLayoutAnimation();
}

private void initRecyclerView() {
    recyclerView = (RecyclerView) findViewById(R.id.recycler);
    recyclerView.setLayoutManager(new GridLayoutManager(this, 2));

}

private void setRecyclerAdapter(RecyclerView recyclerView) {
    RecyclerViewAdapter adapter = new RecyclerViewAdapter(items);
    adapter.setOnItemClickListener(this);
    recyclerView.setAdapter(adapter);
}

private void initFab() {
    findViewById(R.id.fab).setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Snackbar.make(content, "FAB Clicked", Snackbar.LENGTH_SHORT).show();
        }
    });
}

private void initToolbar() {
    final Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);
    final ActionBar actionBar = getSupportActionBar();

    if (actionBar != null) {
        actionBar.setHomeAsUpIndicator(R.drawable.ic_menu_black_24dp);
        actionBar.setDisplayHomeAsUpEnabled(true);
    }
}

private void setupDrawerLayout() {
    drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);

    navigationView = (NavigationView) findViewById(R.id.navigation_view);
    navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
        @Override
        public boolean onNavigationItemSelected(MenuItem menuItem) {
            Snackbar.make(content, menuItem.getTitle() + " pressed", Snackbar.LENGTH_LONG).show();
            menuItem.setChecked(true);
            drawerLayout.closeDrawers();
            return true;
        }
    });
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
        case android.R.id.home:
            drawerLayout.openDrawer(GravityCompat.START);
            return true;
    }

    return super.onOptionsItemSelected(item);
}

@Override
public void onItemClick(View view, ViewModel viewModel) {
    DetailActivity.navigate(this, view.findViewById(R.id.image), viewModel);
}
}

Upvotes: 0

Views: 173

Answers (2)

Abhishek kumar
Abhishek kumar

Reputation: 4445

Below is the sample code for directly logout from menu

NOTE : No need of open new Activity or fragment for logout.

Here is Code:

 @Override
public boolean onNavigationItemSelected(MenuItem item) {
    // Handle navigation view item clicks here.
    int id = item.getItemId();
    if (id == R.id.nav_home) {
        fragment = new HomeFragment();
        title.setText(pref.getString(Constants.REGIS_FIRST_NAME, "")+" "+pref.getString(Constants.REGIS_LAST_NAME, ""));
    }
    if (id == R.id.nav_profile) {
        fragment = new ProfileFragment();
        title.setText("My Profile ");
    }
    if (id == R.id.nav_past) {
        fragment = new PastFragment();
        title.setText("Past Ceremony ");
    } 
     else if (id == R.id.nav_logout) {
        callLogout(); //logout here
    }

Here is the Dialog code :

 private void callLogout() {
    final Dialog dialog1;
    dialog1 = new Dialog(MainActivity.this);
    dialog1.requestWindowFeature(Window.FEATURE_NO_TITLE);
    dialog1.setCancelable(false);
    dialog1.setContentView(R.layout.logout_dilaog);

    final TextView logoutTxt, yes, no;
    yes = dialog1.findViewById(R.id.yes);
    no = dialog1.findViewById(R.id.no);
    logoutTxt = dialog1.findViewById(R.id.logoutTxt);

    Log.e("NAME", "" + pref.getString("USER_NAME_LOGIN", ""));
    logoutTxt.setText("Are you sure to logout ?");

    yes.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            editor = pref.edit();
            editor.clear();
            editor.apply();
            // utils.showtoast("Logout");
            finish();

            Intent intent = new Intent(MainActivity.this, LoginActivity.class);
            intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            startActivity(intent);
        }
    });

    no.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            dialog1.dismiss();
        }
    });
    dialog1.show();
}

logout_dialog.xml

<?xml version="1.0" encoding="utf-8"?>

<TextView
    android:layout_marginTop="10dp"
    android:gravity="center_horizontal"
    android:textSize="16dp"
    android:fontFamily="@font/lato_semibold"
    android:id="@+id/logoutTxt"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:textColor="@color/black" />

<LinearLayout
    android:gravity="right"
    android:layout_marginTop="15dp"
    android:orientation="horizontal"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <TextView
        android:id="@+id/yes"
        android:layout_marginRight="15dp"
        android:layout_width="90dp"
        android:layout_height="30dp"
        android:text="YES"
        android:fontFamily="@font/lato_regular"
        android:gravity="center"
        android:textColor="@color/white"
        android:textSize="14dp"
        android:background="@drawable/ripple_btn"
        />

    <TextView
        android:layout_marginRight="15dp"
        android:id="@+id/no"
         android:layout_width="90dp"
        android:layout_height="30dp"
         android:text="NO"
        android:fontFamily="@font/lato_regular"
        android:gravity="center"
         android:textColor="@color/white"
        android:textSize="14dp"
        android:background="@drawable/ripple_btn"
        />


</LinearLayout>

Upvotes: 0

Yourange
Yourange

Reputation: 158

What if you pass logout actions to a new function , let say logout() and you put inside session.logoutUser(); Intent i = new Intent(MainActivity.this, LoginActivity.class); startActivity(i); finish();

Then, inside onOptionsItemSelected function you add a case check case (menuItem.getTitle =="Logout") {lougout();}

Of course it's just an idea but you can elaborate it

Upvotes: 1

Related Questions