LAINO의 개발노트

Android NavigationView 에서의 정말 간단한 Header 제어 본문

안드로이드/삽질 노트

Android NavigationView 에서의 정말 간단한 Header 제어

Laino 2017. 12. 21. 03:11

안녕하세요 오늘은 제가 몇시간동안 들었던 삽에 대해 간단한 해결책을 공유하고자 합니다.


안드로이드 스튜디오에서는 프로젝트를 생성할때 여러가지 탬플릿들을 제공하고 있는데요,

그중 NavigationView를 이용한 네비게이션 드로어와 관련된 이야기를 해보고자 합니다.


저걸 선택하고 바로 앱을 빌드하면 우리는 따끈한 드로어가 들어있는 앱을 만나볼수 있는데요.

저는 그렇게 프로젝트를 시작해서 이곳저곳 코드를 짜던중,


저는 그중 저기 헤더 부분중에서도 초록색 그라데이션 부분을 제가 원하는대로 바꾸고 싶었습니다.

NavigationView를 사용하게 됨으로써 /drawable/activity_main.xml에는 

1
2
3
4
5
6
7
8
<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" />
cs

이런식으로 네비게이션 뷰가 정의되어있는것을 보실수 있는데요

headerLayout 엘리먼트로 헤더 레이아웃을 지정해주는것을 확인할 수 있었습니다.


nav_header_main.xml 의 내용입니다.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="@dimen/nav_header_height"
    android:background="@drawable/side_nav_bar"
    android:gravity="bottom"
    android:orientation="vertical"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:theme="@style/ThemeOverlay.AppCompat.Dark">
 
    <ImageView
        android:id="@+id/imageView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:paddingTop="@dimen/nav_header_vertical_spacing"
        app:srcCompat="@mipmap/ic_launcher_round" />
 
    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:paddingTop="@dimen/nav_header_vertical_spacing"
        android:text="Android Studio"
        android:textAppearance="@style/TextAppearance.AppCompat.Body1" />
 
    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="android.studio@android.com" />
 
</LinearLayout>
 
cs



현재 저 Layout의 background로 지정되어있는 그라데이션이 저를 지옥행열차로 인도 했던 친구인데요

파일자체는 일단 /drawable/side_nav_bar.xml 이라는 파일에서 정의되어 있습니다.

1
2
3
4
5
6
7
8
9
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle">
    <gradient
        android:angle="135"
        android:centerColor="#009688"
        android:endColor="#00695C"
        android:startColor="#4DB6AC"
        android:type="linear" />
</shape>
cs


일단 저 background 부분을 drawable의 리소스로 바꾸면 잘돌아가는구나, 먼저 인지하였고 여기서 끝나는줄 알았으나,


저는 이미지를 바꾸거나 그럴필요와 고해상도 이미지에 대한 메모리관리의 필요성때문에 저곳을 어떻게 Glide로 제어할수 있을까를 고민하게 되었습니다.


그러던중 해답을 발견합니다 (4시간만에)

https://developer.android.com/reference/android/support/design/widget/NavigationView.html

열심히 레퍼런스를 뒤지던중 getHeaderView() 라는 메소드를 발견하게 됩니다.


구현은 아주-매우 간단합니다


메인 엑티비티 onCreate() 내에서 동작하는 코드입니다.

1
2
3
4
5
6
7
8
9
final View headerView = navigationView.getHeaderView(0);
        Glide.with(this).load(R.drawable.nav_header).into(new SimpleTarget<Drawable>() {
            @Override
            public void onResourceReady(Drawable resource, Transition<super Drawable> transition) {
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
                    headerView.setBackground(resource);
                }
            }
        });
cs


이게 끝이에요.

더이상은 저와같이 삽을 드시는분들이 없길바라며
저같은 경우에 

android navigation drawer image

android navigation drawer background image

android navigation drawer header image

등과 같이 여러 구글형님께 다른 질문을 해보았으나 만족한 답변을 얻지 못했습니다.


꼭 저처럼 삽들러가시는분이 없길 빕니다.


https://github.com/podcastm1/NavigationViewHeaderExample 예제 첨부해두었습니다. 

궁금하신 사항은 laino@laino.ml이나 텔레그램 @laino0527 혹은 댓글로 부탁드립니다.




Comments