Change the Navigation Drawer information from its parent activity [duplicated]

0

Simple, I have a navigation drawer (auto generated by the andorid studio assistant) happens that he generates his main activity which calls the drop-down menu and this in turn is divided into 2 sections ie the header and the body ( that is, the layout invokes another layout) here is where my question is, I want to modify part of the header with any String supplied by the user.

MenuCentral.java class which contains the MenuDrawer

package company.viral.organizadorjec.ActivitysPrincipales;

import android.content.DialogInterface;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.v4.app.FragmentManager;
import android.support.v7.app.AlertDialog;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.support.design.widget.NavigationView;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import company.viral.organizadorjec.FragmentMenu.CaracteristicasF;
import company.viral.organizadorjec.FragmentMenu.PeriodosF;
import company.viral.organizadorjec.FracmentPopUp.ConfiguracionActividadF;
import company.viral.organizadorjec.FracmentPopUp.ConfiguracionMateriaF;
import company.viral.organizadorjec.FracmentPopUp.ConfiguracionPeriodoF;
import company.viral.organizadorjec.FracmentPopUp.ConfiguracionProfesorF;
import company.viral.organizadorjec.FragmentMenu.InicioF;
import company.viral.organizadorjec.FragmentMenu.MateriaF;
import company.viral.organizadorjec.FragmentMenu.PerfilF;
import company.viral.organizadorjec.FragmentMenu.ProfesoresF;
import company.viral.organizadorjec.R;

public class MenuCentral extends AppCompatActivity
        implements NavigationView.OnNavigationItemSelectedListener {

    private PopupWindow popupadicion;
    private DrawerLayout posicionpopup;

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

        TextView correo = (TextView) findViewById(R.id.textviewcorreo);


        correo.setText("Erny");

          posicionpopup = (DrawerLayout) findViewById(R.id.drawer_layout);



        //colocamos el fragment con que inicia el menu

        FragmentManager fragmentManager = getSupportFragmentManager();
        fragmentManager.beginTransaction().replace(R.id.contenedor,new InicioF()).commit();


        //este es el apartado para el botonsito flotante

        FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() {

            //metodo de escucha para el popup
            @Override
            public void onClick(View view) {

               if(popupadicion!=null){
                    popupadicion.dismiss();
               }



                //implementamos el popup
                LayoutInflater inflater = (LayoutInflater)getBaseContext().getSystemService(LAYOUT_INFLATER_SERVICE);
                final View vistaadicion = inflater.inflate(R.layout.activity_pop_adicion,null);

                popupadicion = new PopupWindow(
                        vistaadicion, RelativeLayout.LayoutParams.WRAP_CONTENT,
                        RelativeLayout.LayoutParams.WRAP_CONTENT
                );


                //luego de clicear y abrir el popup le decimos...
                //si das al profe ve a profe
                LinearLayout btnprofe = (LinearLayout) vistaadicion.findViewById(R.id.btnagregarprofesor);
                btnprofe.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {

                        FragmentManager fragmentManager = getSupportFragmentManager();
                        fragmentManager.beginTransaction().replace(R.id.contenedor,new ConfiguracionProfesorF()).commit();
                        popupadicion.dismiss();

                    }
                });
                //si le das actividad ve actividad
                LinearLayout btnactividad = (LinearLayout) vistaadicion.findViewById(R.id.btnagregaractividad);
                btnactividad.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {

                        FragmentManager fragmentManager = getSupportFragmentManager();
                        fragmentManager.beginTransaction().replace(R.id.contenedor,new ConfiguracionActividadF()).commit();
                        popupadicion.dismiss();

                    }
                });
                //si le das a materias ve a materias
                LinearLayout btnmaterias = (LinearLayout) vistaadicion.findViewById(R.id.btnagregarmateria);
                btnmaterias.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {

                        FragmentManager fragmentManager = getSupportFragmentManager();
                        fragmentManager.beginTransaction().replace(R.id.contenedor,new ConfiguracionMateriaF()).commit();
                        popupadicion.dismiss();

                    }
                });
                //si le das a periodo ve a periodo
                LinearLayout btnperiodo = (LinearLayout) vistaadicion.findViewById(R.id.btnagregarperiodo);
                btnperiodo.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {

                        FragmentManager fragmentManager = getSupportFragmentManager();
                        fragmentManager.beginTransaction().replace(R.id.contenedor,new ConfiguracionPeriodoF()).commit();
                        popupadicion.dismiss();

                    }
                });
                //luego le decimos que cierre el popup con el boton

                Button cerrarboton = (Button) vistaadicion.findViewById(R.id.btnpopupcerrar);
                cerrarboton.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        popupadicion.dismiss();
                    }
                });


                //hubicamos donde queremos el popup
                popupadicion.showAtLocation(posicionpopup, Gravity.CENTER,0,0 );
            }
        });

        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 {
            AlertDialog.Builder builder = new AlertDialog.Builder(this);
            builder.setMessage("¿Desea Salir de la Aplicación?");
            builder.setTitle("Alerta!");
            builder.setPositiveButton("SI", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    finish();
                }
            });
            builder.setNegativeButton("NO", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.cancel();
                }
            });

            AlertDialog dialog=builder.create();
            dialog.show();
        }
    }

    @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_central, 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();

        FragmentManager fragmentManager = getSupportFragmentManager();

        if (id == R.id.nav_camera) {
            fragmentManager.beginTransaction().replace(R.id.contenedor,new InicioF()).commit();

        } else if (id == R.id.nav_gallery) {
            fragmentManager.beginTransaction().replace(R.id.contenedor,new ProfesoresF()).commit();

        } else if (id == R.id.nav_slideshow) {
            fragmentManager.beginTransaction().replace(R.id.contenedor,new PeriodosF()).commit();

        } else if (id == R.id.nav_manage) {
            fragmentManager.beginTransaction().replace(R.id.contenedor,new CaracteristicasF()).commit();

        } else if (id == R.id.nav_share) {
            fragmentManager.beginTransaction().replace(R.id.contenedor,new PerfilF()).commit();

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


        } else if (id == R.id.nav_materia){
            fragmentManager.beginTransaction().replace(R.id.contenedor,new MateriaF()).commit();
        }

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


}

as you can see the flame at activity_menu_central.xml which is the following.

activity_menu_central.xml

<?xml version="1.0" encoding="utf-8"?>
<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_menu_central"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />


    <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:fitsSystemWindows="true"
        app:headerLayout="@layout/nav_header_menu_central"
        app:menu="@menu/activity_menu_central_drawer" />

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

which looks like this ...

as you can notice in the xml the layout calls app:headerLayout="@layout/nav_header_menu_central" and in the there is the TextView that I want to modify which is the following ...

nav_header_menu_central.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="@dimen/nav_header_height"
    android:background="@drawable/side_nav_bar"
    android:gravity="bottom"
    android:orientation="vertical"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:theme="@style/ThemeOverlay.AppCompat.Dark">

    <ImageView
        android:id="@+id/imageView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:paddingTop="@dimen/nav_header_vertical_spacing"
        app:srcCompat="@android:drawable/sym_def_app_icon" />

    <TextView
        android:id="@+id/textViewCabeza"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:paddingTop="@dimen/nav_header_vertical_spacing"
        android:text="Bienvenido"
        android:textAppearance="@style/TextAppearance.AppCompat.Body1" />

    <TextView
        android:id="@+id/textviewcorreo"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="*AQUI VA EL NOMBRE*" />

</LinearLayout>

The problem is the following ... MenuCentral.java call activity_menu_central.xml and this invokes the menu, I want to modify the text located in the header " HERE GOES THE NAME "in the xml nav_header_menu_central with my variable" mail "from the MenuCentral

    
asked by ERny JOsé HIdalgo COrrea 20.01.2017 в 00:17
source

1 answer

0

I managed to find the answer after inquiring and inquiring (all thanks to the guys from "SmartGeeks" credit to them)

The answer is given as follows:

As MenuCentral.java calls its own layout it is obvious that declaring the variable in that method would load it null (I as a novice did not know how to do it) to be able to set the changes we simply went down to the line of code where the displacement of the menu is called in ...

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

And implement this small sentence which generate the relevant changes ..

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


        //con esto generamos el usuario en el header del menu-------------------------------
        View hView = navigationView.getHeaderView(0);
        TextView correo = (TextView) hView.findViewById(R.id.textviewcorreo);

        Bundle bundle=getIntent().getExtras();
        int identificar = bundle.getInt("identificador");

        SQLite admin = new SQLite(this,"administracion",null,1);
        SQLiteDatabase bd = admin.getWritableDatabase();

        nombreid=bd.rawQuery("select nombre from usuarios where id='"+identificar+"'",null);

        if (nombreid.moveToFirst()==true) {
            String usuarioid = nombreid.getString(0);
            correo.setText(usuarioid);

        }
        //----------------------------------------------------------------------------------
        navigationView.setNavigationItemSelectedListener(this);

To call them, you must create the Header view in the main class and to do so we must create a View type variable under the NavigationView Instance

Once you have created the View type variable that the HeaderView brings, you can now create the necessary Variables and instantiate them. It must be taken into account that when using the findViewById method that calls the id of each item, the View type variable must be placed at the beginning as shown.

In my case a variable is already loaded from a previous activity (a login) that was loaded by a .putExtra which is captured searched in the database and referred to find the id and thus the name of the user and be able to place it in the header of the menu

and SURPRISE !!! we have an editable Auto Menu depending on the user that enters

    
answered by 20.01.2017 в 20:31