Search code examples
androidlayoutmenuhamburger-menu

Android - setOnClickListern in nav_header_menu


I would add event in nav_header_menu.

I added login and register section then when user click I would show the relative layout page: https://ibb.co/wwmFzSk

I added fragment_layout_user.xml and ActivityLoginUser class with code:

public class ActivityLoginUser extends AppCompatActivity{

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

    ActionBar ab = getSupportActionBar();
    ab.setDisplayHomeAsUpEnabled(true);
}}

How can I implement this event in drawer menu?


Solution

  • I solved it also with @SumitSingh suggestion. I paste here the correct way to solve that.

    We need to add this code in the activity class where we added navigation view.

        NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
    View headerview = navigationView.getHeaderView(0);
    TextView login= (TextView) headerview.findViewById(R.id.login);
    login.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
           // Your code here 
        }
    });
    

    Replace // Your code here with:

    Intent loginUserIntent = new Intent(getContext(), ActivityLoginUser.class);
    
                /* Start the new activity */
                startActivity(loginUserIntent);
    

    If you get error for getContext() please replace it with MainActivity.this

    It works for me.