How to create a class with a NavigationDrawer to use in various Activities?

2

I started studying Android development a short time ago, I saw that to use a NavigationDrawer it is recommended to use fragments to change a FrameLayout in the main Activity, but in the new activities that I create, I did not want to have to put all the NavigationDrawer code again, wanted to know how to create a menu to use on any one.

Does anyone have any tips to get me through?

EDIT:

MainActivity.java

public class MainActivity extends GenericActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        setUpDrawerLayout();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }
        return super.onOptionsItemSelected(item);
    }
}

GenericActivity.java

public class GenericActivity extends AppCompatActivity {

    protected DrawerLayout drawerLayout;
    protected Toolbar toolbar;
    protected boolean drawerLayoutEnable;
    protected NavigationView navigationView;
    protected ActionBarDrawerToggle toggle;

    protected void setUpDrawerLayout(){
        this.drawerLayoutEnable = true;

        toolbar = (Toolbar)findViewById(R.id.toolbar);
        if(toolbar !=null){
            setSupportActionBar(toolbar);
            getSupportActionBar().setDisplayHomeAsUpEnabled(true);
            getSupportActionBar().setHomeButtonEnabled(true);

            drawerLayout = (DrawerLayout)findViewById(R.id.drawer_layout);
            setUpDrawerToggle();
            setUpNavigationView();
        }
    }

    private void setUpNavigationView() {
        navigationView = (NavigationView) findViewById(R.id.nav_view);
        navigationView.setNavigationItemSelectedListener((NavigationView.OnNavigationItemSelectedListener) this);
    }

    private void setUpDrawerToggle(){
        toggle = new ActionBarDrawerToggle(
                this, 
                drawerLayout, 
                toolbar, 
                R.string.navigation_drawer_open, 
                R.string.navigation_drawer_close);
        drawerLayout.setDrawerListener(toggle);
        toggle.syncState();
    }

    @Override
    public void onBackPressed() {
        DrawerLayout drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
        if (drawerLayout.isDrawerOpen(GravityCompat.START)) {
            drawerLayout.closeDrawer(GravityCompat.START);
        } else {
            super.onBackPressed();
        }
    }
}

activity_generic.xml

<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/activity_base"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true"
    tools:context="com.example.rafael.elite.BaseActivity">

    <android.support.design.widget.AppBarLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:theme="@style/AppTheme.AppBarOverlay">

        <android.support.v7.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            android:background="?attr/colorPrimary"
            app:popupTheme="@style/AppTheme.PopupOverlay" />

    </android.support.design.widget.AppBarLayout>

    <android.support.v4.widget.DrawerLayout
        android:id="@+id/drawer_layout" //Seria este o drawer_layout que eu tenho que referenciar?
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_marginTop="?attr/actionBarSize"
        android:fitsSystemWindows="true"
        tools:openDrawer="start">

        <android.support.design.widget.NavigationView
            android:id="@+id/nav_view"
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:layout_gravity="start"
            android:paddingTop="24dp"
            app:headerLayout="@layout/nav_drawer_header"
            app:menu="@menu/menu_generic_activity" />

</android.support.v4.widget.DrawerLayout>

    
asked by anonymous 15.12.2015 / 14:12

1 answer

2

Well, that was a question I came across when I decided to implement NavigationDrawer also in my app, mainly because I would like to have activities in which I used it and other activities that I did not use. And most of all, I did not want to duplicate code for the classes, so after researching in a number of tutorials I adapted and I came up with this result in a summary way, but you will understand the concept.

I created a GenericActivity where all the other activities of my application will extend it:

public abstract class GenericActivity extends AppCompatActivity {
    protected DrawerLayout drawerLayout;
    protected ActionBarDrawerToggle drawerToggle;
    protected NavigationView navigationView;
    protected NavigationViewMenuHandler navigationMenuHandler;
    //Com essa variável eu valido se a activity possui o NavigationDrawer
    //para realizar determinadas ações, ou não.
    protected boolean drawerLayoutEnable;

    //esse método é chamado pelas activities que extendem esta classe
    //e desejam ter um NavigationDrawer.
    protected void setUpDrawerLayout() {
        this.drawerLayoutEnable = true;

        //Toda a lógica de criação do NavigationDrawer vai neste método
        //Atualize com suas regras caso necessário
        ActionBar actionBar = getSupportActionBar();
        if (actionBar != null) {
            actionBar.setHomeAsUpIndicator(R.drawable.ic_menu_black_36dp);
            actionBar.setDisplayHomeAsUpEnabled(true);

            drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
            setUpDrawerToggle(); //configura o DrawerToggle
            setUpNavigationView(); //configura a NavigationView
        }
    }

    //Métodos private setUpDrawerToggle() e setUpNavigationView()
}

Now all activities of my application that wish to have the same NavigationDrawer configured extend GenericActivity and only call the setUpDrawerLayout() method in onCreate() .

For example:

public class AppFootActivity extends GenericActivity {

    @Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setContentView(R.layout.app_activity);
        //Chamo a configuração do NavigationDrawer. Caso eu não queira que
        //minha activity tenha um, basta não chamá-lo.
        setUpDrawerLayout();

        //Demais códigos da activity
    }

}

This same logic can be applied to other components such as the ToolBar.

I took into consideration that you already know how to implement NavigationDrawer and only have doubts about how to do it in various activities.

Hug.

    
15.12.2015 / 16:08