메뉴 건너뛰기

?

단축키

Prev이전 문서

Next다음 문서

크게 작게 위로 아래로 댓글로 가기 인쇄 첨부
?

단축키

Prev이전 문서

Next다음 문서

크게 작게 위로 아래로 댓글로 가기 인쇄 첨부

내비게이션 드로어(Navigation Drawer)는 앱에서 사용 가능한 기능을 탐색할 수 있도록 Menu를 제공하는 화면입니다. 기본적으로 화면의 가장자리에 숨겨져 있으며 왼쪽에서 오른쪽으로 스와이프 동작을 수행하거나 App Bar의 아이콘을 클릭하여 화면에 표시할 수 있습니다.

 

 

 


1. 드로어 네비게이션(Drawer Navigation) 구현

1.1 메인 액티비티(Activity) 레이아웃 리소스

<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/drawer_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true"
    tools:openDrawer="start">

    <include
        layout="@layout/appbar"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

    <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:menu="@menu/drawerlayout"
        app:headerLayout="@layout/header"/>

</android.support.v4.widget.DrawerLayout>

Drawer Navigation을 화면에 추가하기 위해서는 화면의 최상단 레이아웃은 DrawerLayout이 배치되어야 합니다. 그 아래 자식 뷰들의 배치 순서는 Main 화면에 표시되는 자식 뷰들이 먼저 오고 Drawer로 사용될 뷰의 경우는 마지막으로 배치하게 됩니다. Main 화면에 배치되는 위젯은 ToolbarLayout 아래에 배치된 Toolbar 하나만 배치된 형태로 해당 영역은 레이아웃 리소스 파일을 따로 정의해두고 <include> 요소를 통해 해당 레이아웃 리소스에 포함시키는 형태를 가집니다.  아래는 /res/layout/appbar.xml의 내용으로 Main 화면에 배치되는 자식 뷰가 정의된 레이아웃 리소스입니다.

<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <android.support.design.widget.AppBarLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <android.support.v7.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            android:background="?attr/colorPrimary" />
    </android.support.design.widget.AppBarLayout>

</android.support.design.widget.CoordinatorLayout>

다음으로 Drawer에 배치되는 자식 뷰로 해당 예제에서 NavigationView를 배치하였습니다. NavigationView는 크게 Header 영역과 Content 영역으로 나누어집니다. 

 

Header 영역의 화면을 구성할 레이아웃 리소스는 headerLayout 속성의 속성 값을 지정합니다. 속성 값으로는 레이아웃 리소스 ID 값이 넘어가고 해당 파일은 /res/layout/header.xml 경로에 위치합니다. 

<?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="200dp"
    android:background="@color/cardview_dark_background"
    android:gravity="center"
    android:orientation="vertical"
    android:theme="@style/ThemeOverlay.AppCompat.Dark">

    <TextView
        android:id="@+id/text"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Select Item"
        android:textSize="50dp" />

</LinearLayout>

 다음으로 Content 영역을 구성하기 위해서는 Menu 레이아웃 리소스가 정의된 파일의 리소스 ID를 menu 속성 값으로 지정합니다. 경로는 /res/menu/drawerlayout.xml 위치합니다.

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">

    <item
        android:id="@+id/menuitem1"
        android:title="menuItem1" />
    <item
        android:id="@+id/menuitem2"
        android:title="menuItem2" />
    <item
        android:id="@+id/menuitem3"
        android:title="menuItem3" />
</menu>

 

 

 

 


1.2 Drawer Navigation 추가하기

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        
        this.InitializeLayout();
    }
    
    public void InitializeLayout()
    {
    	//toolBar를 통해 App Bar 생성
        Toolbar toolbar = findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        
        //App Bar의 좌측 영영에 Drawer를 Open 하기 위한 Incon 추가
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        getSupportActionBar().setHomeAsUpIndicator(R.mipmap.ic_launcher);

        DrawerLayout drawLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
        NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);

        ActionBarDrawerToggle actionBarDrawerToggle = new ActionBarDrawerToggle(
                this,
                drawLayout,
                toolbar,
                R.string.open,
                R.string.closed
        );

        drawLayout.addDrawerListener(actionBarDrawerToggle);
    }

1.3 Navigation의 Item 클릭에 대한 이벤트 처리

        navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
            @Override
            public boolean onNavigationItemSelected(@NonNull MenuItem menuItem) {
                switch (menuItem.getItemId())
                {
                    case R.id.menuitem1:
                        Toast.makeText(getApplicationContext(), "SelectedItem 1", Toast.LENGTH_SHORT).show();
                    case R.id.menuitem2:
                        Toast.makeText(getApplicationContext(), "SelectedItem 2", Toast.LENGTH_SHORT).show();
                    case R.id.menuitem3:
                        Toast.makeText(getApplicationContext(), "SelectedItem 3", Toast.LENGTH_SHORT).show();
                }

                DrawerLayout drawer = findViewById(R.id.drawer_layout);
                drawer.closeDrawer(GravityCompat.START);
                return true;
            }
        });

▼ Drawer Navigation에서 MenuItem 클릭에 대한 이벤트 처리를 위해 Listener를 등록합니다. MenuItem이 클릭되면 drawer를 닫아주기 위해 closeDrawer()를 호출하고 있습니다.

1.4 이전 버튼 클릭 시 Drawer 닫기

    @Override
    public void onBackPressed() {
        DrawerLayout drawer = findViewById(R.id.drawer_layout);
        if (drawer.isDrawerOpen(GravityCompat.START)) {
            drawer.closeDrawer(GravityCompat.START);
        } else {
            super.onBackPressed();
        }
    }

 이전 버튼을 클릭하였을 때 Drawer가 Open 상태라면 closeDrawer()를 통해 Drawer를 닫아주도록 합니다. 

 

 

 

 


List of Articles
번호 제목 날짜 조회 수
237 안드로이드 - Serializable를 활용한 다른 액티비티에 객체(Object) 전달하기 file 2021.03.31 281
236 안드로이드 - 문자열 리소스를 활용한 다국어 지원 file 2021.03.31 282
235 안드로이드 - SnackBar를 사용해 팝업창 띄우기 file 2021.03.31 282
234 안드로이드 - 옵션 메뉴 (Option Menu) 구현 방법 file 2021.04.01 283
233 초기화면 페이지를 만들어보자. splash 페이지 제작 file 2020.12.14 285
232 Java에서 XML 불러와서 동적 변화 주기 file 2021.03.31 288
231 줄바꿈 문자 치환 2020.12.14 289
230 [하이브리드앱] 링크를 웹뷰가 아닌 새로운 브라우저에서 열기 2021.09.30 293
229 패키지명을 한꺼번에 변경하기 (Refactor) file 2020.12.14 295
228 앱 번들(Android App Bundle) 만들기 file 2021.09.14 305
227 android.support.v4.content.FileProvider not found file 2020.12.14 308
226 안드로이드 - 리니어 레이아웃 (Linear Layout) file 2021.03.29 319
225 안드로이드 - 토스트(Toast) 메시지 사용하기. file 2021.03.31 321
224 안드로이드 - 뷰페이저(ViewPager) 구현 file 2021.04.02 323
223 안드로이드 - 명시적 인텐트(Explicit Intent)와 암시적 인텐트 (Implicit Intent) file 2021.04.01 324
222 안드로이드 앱배포하기 apk 만들기 file 2020.12.14 326
221 안드로이드 arrayList 를 Json으로 변환 / jsonarry file 2021.03.29 326
220 Firebase - 푸시알림 보내기 file 2021.09.30 339
219 Volley 이용시에 한글 깨질때 UTF-8로 변경 2020.12.14 343
218 안드로이드 - 버튼 이벤트 처리방법 정리 (리스너 구현 및 이벤트 핸들링) file 2021.03.31 343
Board Pagination Prev 1 2 3 4 5 6 7 8 9 10 ... 13 Next
/ 13

하단 정보를 입력할 수 있습니다

© k2s0o1d4e0s2i1g5n. All Rights Reserved