How to add only a few Activity navigation Drawer

Asked

Viewed 521 times

1

I’m having a question how I can add the navigation Drawer the left side menu in some activities. I started the project by Blakactivity and now the need to add the side menu has arisen. I already have the MainActivity. Added by Android Studio itself.

public class MainActivity extends AppCompatActivity
        implements NavigationView.OnNavigationItemSelectedListener {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
                        .setAction("Action", null).show();
            }
        });

        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
                this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
        drawer.setDrawerListener(toggle);
        toggle.syncState();

        NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
        navigationView.setNavigationItemSelectedListener(this);
    }

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

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.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);
    }

    @SuppressWarnings("StatementWithEmptyBody")
    @Override
    public boolean onNavigationItemSelected(MenuItem item) {
        // Handle navigation view item clicks here.
        int id = item.getItemId();

        if (id == R.id.nav_camera) {
            // Handle the camera action
        } else if (id == R.id.nav_gallery) {

        } else if (id == R.id.nav_slideshow) {

        } else if (id == R.id.nav_manage) {

        } else if (id == R.id.nav_share) {

        } else if (id == R.id.nav_send) {

        }

        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        drawer.closeDrawer(GravityCompat.START);
        return true;
    }
}

For example this Activity I need to add to it the Side menu follows the code:

public class DadosCadastraisActivity extends AppCompatActivity  implements View.OnClickListener{

    public EditText edtNome;
    private EditText edtCnpjCpf;
    private EditText edtRgIe;
    private EditText edtCep;
    private EditText edtUf;
    private EditText edtCidade;
    private EditText edtBairro;
    private EditText edtEndereco;
    private EditText edtnumero;
    private EditText edtComplemento;
    private EditText edtFoneComercial;
    private EditText edtFoneResidencial;
    private EditText edtFoneCelular;
    private EditText edtEmail;
    private DatabaseHelper databaseHelper;
    private PessoaDao pessoaDao;
    private Pessoa pessoa;
    private LoginDao loginDao;
    private LoginSeralizable login;
    public Button btnEnviarDados;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_dados_cadastrais);
        if (android.os.Build.VERSION.SDK_INT > 9)
        {
            StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
            StrictMode.setThreadPolicy(policy);
        }

        btnEnviarDados = (Button) findViewById(R.id.btnEnviarDados);
        btnEnviarDados.setOnClickListener(this);


        databaseHelper = new DatabaseHelper(DadosCadastraisActivity.this);



                try {


                    pessoaDao = new PessoaDao(databaseHelper.getConnectionSource());
                    pessoa = pessoaDao.queryForId(1);

                    edtNome = (EditText) findViewById(R.id.edtNome);
                    edtNome.setText(pessoa.getNome());

                    edtCnpjCpf = (EditText) findViewById(R.id.edtCnpjCpf);

                    if (pessoa.getCnpjCpf().length()==11){
                        edtCnpjCpf.addTextChangedListener(Mask.insert(Mask.CPF_MASK, edtCnpjCpf));
                    }else {
                        edtCnpjCpf.addTextChangedListener(Mask.insert(Mask.CNPJ_MASK, edtCnpjCpf));
                    }

                    edtCnpjCpf.setText(pessoa.getCnpjCpf());

                    edtRgIe = (EditText) findViewById(R.id.edtRgIe);
                    edtRgIe.setText(pessoa.getRgIE());

                    edtCep = (EditText) findViewById(R.id.edtCEP);
                    edtCep.addTextChangedListener(Mask.insert(Mask.CEP_MASK, edtCep));
                    edtCep.setText(pessoa.getCep());


                    edtUf = (EditText) findViewById(R.id.edtUF);
                    edtUf.setText(pessoa.getUf());

                    edtCidade = (EditText) findViewById(R.id.edtCidade);
                    edtCidade.setText(pessoa.getCidade());

                    edtBairro = (EditText) findViewById(R.id.edtBairro);
                    edtBairro.setText(pessoa.getBairro());

                    edtEndereco = (EditText) findViewById(R.id.edtEndereco);
                    edtEndereco.setText(pessoa.getEndereco());

                    edtnumero = (EditText) findViewById(R.id.edtNumero);
                    edtnumero.setText(pessoa.getNumero());

                    edtComplemento = (EditText) findViewById(R.id.edtComplemento);
                    edtComplemento.setText(pessoa.getComplemento());

                    edtFoneComercial = (EditText) findViewById(R.id.edtFoneComercial);

                    if (pessoa.getFoneComercial().length()!=0){
                        edtFoneComercial.addTextChangedListener(Mask.insert(Mask.TELEFONE_MASK, edtFoneComercial));
                    }

                    edtFoneComercial.setText(pessoa.getFoneComercial());

                    edtFoneResidencial = (EditText) findViewById(R.id.edtFoneResidencial);

                    if (pessoa.getFoneResidencial().length()!=0){
                        edtFoneResidencial.addTextChangedListener(Mask.insert(Mask.TELEFONE_MASK, edtFoneResidencial));
                    }


                    edtFoneResidencial.setText(pessoa.getFoneResidencial());

                    edtFoneCelular = (EditText) findViewById(R.id.edtFoneCelular);
                    edtFoneCelular.addTextChangedListener(Mask.insert(Mask.CELULAR_MASK,edtFoneCelular));
                    edtFoneCelular.setText(pessoa.getFoneCelular());

                    edtEmail = (EditText) findViewById(R.id.edtEmail);
                    edtEmail.setText(pessoa.getEmail());


                } catch (SQLException e) {
                    e.printStackTrace();
                }


            }

    @Override
    public void onClick(View v) {

          new Thread(new Runnable() {
              @Override
              public void run() {

                      DadosCadastraisActivity.this.runOnUiThread(new Runnable() {
                          public void run() {

                              try {
                                  loginDao = new LoginDao(databaseHelper.getConnectionSource());
                                  login = loginDao.queryForId(1);
                              } catch (SQLException e) {
                                  e.printStackTrace();
                              }


                              DadosCadastraisSerealizable dados = new DadosCadastraisSerealizable();


                              dados.codigo= String.valueOf(login.getCodigoCliente());
                              dados.usuario=login.usuario;
                              dados.senha=login.senha;

                              //expressão regular para enviar somente o numeros.


                              dados.cep= edtCep.getText().toString().replaceAll("[^0-9]", "");
                              dados.bairro= edtBairro.getText().toString();

                              dados.endereco= edtEndereco.getText().toString();
                              dados.numero= edtnumero.getText().toString();
                              dados.complemento= edtComplemento.getText().toString();
                              dados.foneComercial= edtFoneComercial.getText().toString().replaceAll("[^0-9]", "");
                              dados.foneResidencial= edtFoneResidencial.getText().toString().replaceAll("[^0-9]", "");
                              dados.foneCelular= edtFoneCelular.getText().toString().replaceAll("[^0-9]", "");
                              dados.email= edtEmail.getText().toString();

                              final WebService ws = new WebService();

                              try {
                                  ws.atuzalizarCadastroCliente(dados);
                              } catch (IOException e) {
                                  e.printStackTrace();
                              } catch (XmlPullParserException e) {
                                  e.printStackTrace();
                              }

                              Toast.makeText(getApplicationContext(), ws.strFault, Toast.LENGTH_SHORT).show();
                          }
                      });




              }

          }).start();



    }


    }
  • I did not understand your question! You te an Activity and that add the side menu in it?

  • I want almost all my Ctivity to have the side menu on it, @Thiagoluizdomacoski

  • So the ones that will have the Side Menu will actually be Fragment’s, and the ones that don’t, will be normal Activity’s!

  • In case these Activitys are already created, just switch to Fragment’s? @Thiagoluizdomacoski

  • 2

    I don’t understand your problem since normally the problem is adding a Drawer navigation, or have all Activities with it, without repeating code

  • Look at the link @ramaral commented on! Fits perfectly with your case!

  • I will look, but I edited the question tbm, if you can take one more look please, @Thiagoluizdomacoski

  • @Rodrigo.oliveira the Nav Drawer is always "stuck" to an Activity, so if you want it on multiple "screens" of your program, you need to use the strategy of Fragments, only exchanging the content of a central Activity that coordinates everything.

Show 3 more comments

1 answer

2


If you work with activities and want the Drawer in some, you should put the codes, the XML and Java:

Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

              DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
                this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
        drawer.setDrawerListener(toggle);
        toggle.syncState();

        NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
        navigationView.setNavigationItemSelectedListener(this);

only the ones you want. Then it will appear only in those.

EDIT:

XML Main:

<android.support.v4.widget.DrawerLayout 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/drawer_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true"
    tools:openDrawer="start"
    >

        <include
            layout="@layout/app_bar_main"
            android:layout_width="match_parent"
            android:layout_height="wrap_content" />

..........................
..........................

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

XML Outra Activity:

<android.support.v4.widget.DrawerLayout 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/drawer_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true"
    tools:openDrawer="start"
    >

        <include
            layout="@layout/app_bar_main"
            android:layout_width="match_parent"
            android:layout_height="wrap_content" />

..........................
..........................

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

Codigo Main:

public class MainActivity extends AppCompatActivity
        implements NavigationView.OnNavigationItemSelectedListener {

    Intent intent;
    private MapController mapController;
    private ShareActionProvider mShareActionProvider;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
                this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
        drawer.setDrawerListener(toggle);
        toggle.syncState();

        NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
        navigationView.setNavigationItemSelectedListener(this);
}

 @Override
    public boolean onNavigationItemSelected(MenuItem item) {
    //codigo da main
}

Another Activity must have these same codes implemented. Ex.:

public class RotaActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener {

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

        //Incluindo a toolbar
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
                this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
        drawer.setDrawerListener(toggle);
        toggle.syncState();

        NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
        navigationView.setNavigationItemSelectedListener(this);
}

 @Override
    public boolean onNavigationItemSelected(MenuItem item) {
//mesmo codigo da main
}
  • Using this way gave this error: This Activity already has an action bar supplied by the window Color. Do not request Window.FEATURE_SUPPORT_ACTION_BAR and set windowActionBar to false in your Theme to use a Toolbar Instead.

  • implemented navigation, just like in main? implements NavigationView.OnNavigationItemSelectedListener

  • yes, implemetei, when I added this code the same android studio already asked to implement.

  • Your Activity layout XML is not in the post, but I believe it has to come with the : <android.support.v4.widget.DrawerLayout &#xA; tools:openDrawer="start"&#xA; >&#xA;&#xA; <include&#xA; layout="@layout/app_bar_main"&#xA; android:layout_width="match_parent"&#xA; android:layout_height="wrap_content" />&#xA;</android.support.v4.widget.DrawerLayout> This Drawer tag about everything, probably as it is in main’s XML

  • I will edit my reply with an example

Browser other questions tagged

You are not signed in. Login or sign up in order to post.