I am trying to change the text in TextView during the program execution to the data sent from a different activity.
The TextView id="@+id/userName"
is in my nav_header_main layout file
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent" android:layout_height="@dimen/nav_header_height"
android:background="@color/primary_dark_material_dark"
android:theme="@style/ThemeOverlay.AppCompat.Dark" android:orientation="vertical"
android:gravity="bottom"
android:weightSum="1"
android:id="@+id/navigation_view">
<ImageView android:layout_width="83dp" android:layout_height="wrap_content"
android:paddingTop="@dimen/nav_header_vertical_spacing"
android:src="@mipmap/user" android:id="@+id/imageView"
android:layout_weight="0.84" />
<TextView
android:id="@+id/userName"
android:layout_width="match_parent" android:layout_height="wrap_content"
android:paddingTop="@dimen/nav_header_vertical_spacing"
android:text="hello"
android:textAppearance="@style/TextAppearance.AppCompat.Body1" />
<TextView android:layout_width="wrap_content" android:layout_height="wrap_content"
android:text="hello" android:id="@+id/userDetail" />
</LinearLayout>
and it is included in main.xml as
<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_main" app:menu="@menu/activity_main_drawer" />
I tried to set the text by OnCreate method
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
NavigationView nav_view= (NavigationView)findViewById(R.id.nav_view);
userName = (TextView) nav_view.findViewById(R.id.userName);
String user = getIntent().getExtras().getString("User");
userName.setText(user); //user is a string
but still I am getting the "Null Pointer Error" during execution. Did I miss something to get things working correctly?
For future users:
First, you need to get the header view: View header = nav_view.getHeaderView(0);
Then get your widgets: userName = (TextView) header.findViewById(R.id.userName);