Update data from a nav header menu from a fragment on Android

-1

I'm new to Stack, my question is this: I want to change the user and mail text of a nav header from a fragment. I have an application that when logging passes some parameters to the menuActivity and from there I update the data of the nav header, all right there. But my menu has a fragment where I can also update the data but I can not get it updated in the navheader. Is there any way to achieve it? From the activity I updated the navheader in the following way:

MenuActivity.java

 NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
    navigationView.setNavigationItemSelectedListener(this);
 View header = navigationView.getHeaderView(0);
    txtUser = (TextView) header.findViewById(R.id.txtUser);
    txtEmail = (TextView) header.findViewById(R.id.textViewPass);
    txtUser.setText(variables.vUsuario);
    txtEmail.setText(variables.vCorreo);

How can I apply that method in a fragment? since I can not use (this) in a fragment and the navigationView.getHeaderView (0) marks me with some type of null error.

Thanks in advance. I'm new to this part of Android.

    
asked by Juananhelo 16.11.2017 в 06:01
source

1 answer

0

Good morning,

To do this you must create a method in activity and call it from the fragmento that you have associated with said activity :

ActivityX

public void changeNavHeaderData(){
    View header = navigationView.getHeaderView(0);
    txtUser = (TextView) header.findViewById(R.id.txtUser);
    txtEmail = (TextView) header.findViewById(R.id.textViewPass);
    txtUser.setText(variables.vUsuario);
    txtEmail.setText(variables.vCorreo);
}

Fragment

((ActivityX)getActivity()).changeNavHeaderData();

Although it is advisable to set activity in onAttach to avoid possible nullPointers:

    ActivityX activityX;

   @Override
     public View onCreateView(LayoutInflater inflater, 
                             ViewGroup container, 
                             Bundle savedInstanceState) {
        activityX.changeNavHeaderData();
     }

     @Override
     public void onAttach(Context context) {
        super.onAttach(context);
            activityX = (Activity) context;
     }
    
answered by 16.11.2017 в 11:05