JavaOgreniyor
JavaOgreniyor

Reputation: 31

setText in Navigation Drawer

How to set text to view from drawer header layout in navigation drawer ?

protected void onCreate(Bundle savedInstanceState) {

[...]

 NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
 navigationView.setNavigationItemSelectedListener(this);
 TextView name = findViewById(R.id.username);
 name.setText(R.string.af_anasayfa_af_butonu);

}

Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setText(int)' on a null object reference ..

Upvotes: 0

Views: 217

Answers (3)

Intsab Haider
Intsab Haider

Reputation: 3571

use this to change the text of material Drawer

navigationView.getMenu().getItem(0).setTitle("any text");

or

navigationView.getMenu().findItem(R.id.nav_calculator).setTitle("xxx");

Secondly your method of getting string is also not right the right way is

String s= getResources().getString(R.string.appbar_scrolling_view_behavior); 

Upvotes: 4

Farrokh
Farrokh

Reputation: 1167

TextView name = findViewById(R.id.username);

this is wrong because username is in the navigationHeader and not in view

so, you should to get NavigationHeader and then get username
for example

TextView name = navigationView.getHeaderView(0).findViewById(R.id.username);

Upvotes: 0

navylover
navylover

Reputation: 13619

You could try this:

TextView name = (TextView) navigationView.getHeaderView(0).findViewById(R.id.username);

Upvotes: 1

Related Questions