Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Customising NavigationView - Adding dynamic headerView, Android Support Design Library

I tried the navigationView from the new android support design library. I want to have a dynamic headerview. Basically, my headerview will show something like quote of the day. I have like around 10 quotes and i want to randomly select a quote and display in a textview in the headerView. I also want to add onClick method for the headerView.

Right now, I don't see any possibilities of changing the headerview layout programmatically. Any suggestions to implement this?

like image 963
Abdul Rahman Avatar asked Jun 03 '15 13:06

Abdul Rahman


3 Answers

first create header XML like lay_header.xml

<TextView
    android:id="@+id/tvThought"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content" />

on your java file inflate this above header in a TextView. like

TextView headerView = (TextView) LayoutInflater.from(this).inflate(R.layout.lay_header, null);
headerView.setText("Your_thoght");

Now add it as a HeaderView

navView = (NavigationView) findViewById(R.id.navView);
navView.addHeaderView(headerView);

Thats it...

like image 67
Moinkhan Avatar answered Oct 17 '22 11:10

Moinkhan


After the new support library update (23.1.1),

You could do this -

Add the headerview in the app:headerLayout="@layout/drawer_header" inside NavigationView.

Then, you can access it by,

View header = navigationView.getHeaderView(0);
TextView text = (TextView) header.findViewById(R.id.textView);

or if you have multiple headers

navigationView.getHeaderCount()

Ref : https://code.google.com/p/android/issues/detail?id=190226#c31

like image 36
RmK Avatar answered Oct 17 '22 11:10

RmK


TextView txt2;
txt2 = (TextView) navigationView.inflateHeaderView(R.layout.nav_header_main).findViewById(R.id.textView2);
txt2.setText("wow! It works like a charm");
like image 6
Shwarz Andrei Avatar answered Oct 17 '22 10:10

Shwarz Andrei