Computer >> 컴퓨터 >  >> 프로그래밍 >> Android

안드로이드에서 커스텀 내비게이션 드로어(탐색 창) 만드는 방법

내비게이션 드로어(Navigation Drawer)는 화면 가장자리에서 좌우로 슬라이드하여 열리는 메뉴 패널로, 대부분의 구글 앱(Gmail, 유튜브 등)에서 흔히 볼 수 있는 UI 요소입니다. 이 글에서는 안드로이드 스튜디오에서 DrawerLayoutNavigationView를 활용해 커스텀 내비게이션 드로어를 단계별로 구현하는 방법을 알아보겠습니다.

1단계 — 새 프로젝트 생성

안드로이드 스튜디오에서 File ⇒ New Project로 이동해 새 프로젝트를 생성하고, 프로젝트 생성에 필요한 모든 정보를 입력합니다.

2단계 — 메인 레이아웃 작성

res/layout/activity_main.xml 파일에 아래 코드를 추가합니다. 전체 화면을 감싸는 DrawerLayout 안에 앱 바(app_bar_main)와 NavigationView가 포함된 구조입니다.

<? xml version= "1.0" encoding= "utf-8" ?>
<android.support.v4.widget.DrawerLayout
   xmlns: android = "https://schemas.android.com/apk/res/android"
   xmlns: app = "https://schemas.android.com/apk/res-auto"
   xmlns: tools = "https://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/app_bar_main"
      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 :headerLayout= "@layout/nav_header_main"
      app :menu= "@menu/activity_main_drawer" />
</android.support.v4.widget.DrawerLayout>

3단계 — 드로어 헤더 레이아웃 작성

res/layout/nav_header_main.xml 파일에 아래 코드를 추가합니다. 헤더에는 프로필 이미지와 제목·부제목 텍스트가 세로로 배치됩니다.

<? xml version= "1.0" encoding= "utf-8" ?>
<LinearLayout xmlns: android = "https://schemas.android.com/apk/res/android"
   xmlns: app = "https://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 :paddingLeft= "@dimen/activity_horizontal_margin"
   android :paddingTop= "@dimen/activity_vertical_margin"
   android :paddingRight= "@dimen/activity_horizontal_margin"
   android :paddingBottom= "@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 :contentDescription= "@string/nav_header_desc"
      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= "@string/nav_header_title"
      android :textAppearance= "@style/TextAppearance.AppCompat.Body1" />
   <TextView
      android :id= "@+id/textView"
      android :layout_width= "wrap_content"
      android :layout_height= "wrap_content"
      android :text= "@string/nav_header_subtitle" />
</LinearLayout>

4단계 — 앱 바 레이아웃 작성

res/layout/app_bar_main.xml 파일에 아래 코드를 추가합니다. 툴바와 플로팅 액션 버튼(FAB)이 포함된 CoordinatorLayout 구조입니다.

<? xml version= "1.0" encoding= "utf-8" ?>
<android.support.design.widget.CoordinatorLayout
   xmlns: android = "https://schemas.android.com/apk/res/android"
   xmlns: app = "https://schemas.android.com/apk/res-auto"
   xmlns: tools = "https://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 :theme= "@style/AppTheme.AppBarOverlay" >
   <android.support.v7.widget.Toolbar
      android :id= "@+id/toolbar"
      android :layout_width= "match_parent"
      android :layout_height= "?attr/actionBarSize"
      android :background= "?attr/colorPrimary"
      app :popupTheme= "@style/AppTheme.PopupOverlay" />
   </android.support.design.widget.AppBarLayout>
   <include layout= "@layout/content_main" />
   <android.support.design.widget.FloatingActionButton
      android :id= "@+id/fab"
      android :layout_width= "wrap_content"
      android :layout_height= "wrap_content"
      android :layout_gravity= "bottom|end"
      android :layout_margin= "@dimen/fab_margin"
      app :srcCompat= "@android:drawable/ic_dialog_email" />
</android.support.design.widget.CoordinatorLayout>

5단계 — 콘텐츠 레이아웃 작성

res/layout/content_main.xml 파일에 아래 코드를 추가합니다. 실제 콘텐츠가 표시되는 영역으로, 필요에 따라 원하는 위젯을 배치하면 됩니다.

<? xml version= "1.0" encoding= "utf-8" ?>
<android.support.constraint.ConstraintLayout
   xmlns: android = "https://schemas.android.com/apk/res/android"
   xmlns: app = "https://schemas.android.com/apk/res-auto"
   xmlns: tools = "https://schemas.android.com/tools"
   android :layout_width= "match_parent"
   android :layout_height= "match_parent"
   app :layout_behavior= "@string/appbar_scrolling_view_behavior"
   tools :context= ".MainActivity"
   tools :showIn= "@layout/app_bar_main" >
</android.support.constraint.ConstraintLayout>

6단계 — 드로어 메뉴 정의

res/menu/activity_main_drawer.xml 파일에 아래 코드를 추가합니다. 카메라, 갤러리, 슬라이드쇼, 도구 항목을 하나의 그룹으로 묶고, 공유·보내기 항목은 별도의 'Communicate' 섹션으로 구성했습니다.

<? xml version= "1.0" encoding= "utf-8" ?>
<menu xmlns: android = "https://schemas.android.com/apk/res/android"
   xmlns: tools = "https://schemas.android.com/tools"
   tools :showIn= "navigation_view" >
   <group android :checkableBehavior= "single" >
      <item
         android :id= "@+id/nav_camera"
         android :icon= "@drawable/ic_menu_camera"
         android :title= "Import" />
      <item
         android :id= "@+id/nav_gallery"
         android :icon= "@drawable/ic_menu_gallery"
         android :title= "Gallery" />
      <item
         android :id= "@+id/nav_slideshow"
         android :icon= "@drawable/ic_menu_slideshow"
         android :title= "Slideshow" />
      <item
         android :id= "@+id/nav_manage"
         android :icon= "@drawable/ic_menu_manage"
         android :title= "Tools" />
   </group>
   <item android :title= "Communicate" >
      <menu>
         <item
            android :id= "@+id/nav_share"
            android :icon= "@drawable/ic_menu_share"
            android :title= "Share" />
         <item
            android :id= "@+id/nav_send"
            android :icon= "@drawable/ic_menu_send"
            android :title= "Send" />
      </menu>
   </item>
</menu>

7단계 — MainActivity 자바 코드 작성

src/MainActivity.java 파일에 아래 코드를 추가합니다. ActionBarDrawerToggle을 통해 툴바와 드로어를 연결하고, 메뉴 클릭 이벤트를 처리합니다.

package app.tutorialspoint.com.sample ;
import android.os.Bundle ;
import android.support.annotation. NonNull ;
import android.support.design.widget.FloatingActionButton ;
import android.support.design.widget.Snackbar ;
import android.view.View ;
import android.support.design.widget.NavigationView ;
import android.support.v4.view.GravityCompat ;
import android.support.v4.widget.DrawerLayout ;
import android.support.v7.app.ActionBarDrawerToggle ;
import android.support.v7.app.AppCompatActivity ;
import android.support.v7.widget.Toolbar ;
import android.view.Menu ;
import android.view.MenuItem ;
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
   @Override
   protected void onCreate (Bundle savedInstanceState) {
      super .onCreate(savedInstanceState) ;
      setContentView(R.layout. activity_main ) ;
      Toolbar toolbar = findViewById(R.id. toolbar ) ;
      setSupportActionBar(toolbar) ;
      FloatingActionButton fab = findViewById(R.id. fab ) ;
      fab.setOnClickListener( new View.OnClickListener() {
         @Override
         public void onClick (View view) {
            Snackbar. make (view , "Replace with your own action" ,
            Snackbar. LENGTH_LONG )
            .setAction( "Action" , null ).show() ;
         }
      }) ;
      DrawerLayout drawer = findViewById(R.id. drawer_layout ) ;
      ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
      this, drawer , toolbar , R.string. navigation_drawer_open ,
      R.string. navigation_drawer_close ) ;
      drawer.addDrawerListener(toggle) ;
      toggle.syncState() ;
      NavigationView navigationView = findViewById(R.id. nav_view ) ;
      navigationView.setNavigationItemSelectedListener( this ) ;
   }
   @Override
   public void onBackPressed () {
      DrawerLayout drawer = findViewById(R.id. drawer_layout ) ;
      if (drawer.isDrawerOpen(GravityCompat. START )) {
         drawer.closeDrawer(GravityCompat. START ) ;
      } else {
         super .onBackPressed() ;
      }
   }
   @Override
   public boolean onCreateOptionsMenu (Menu menu) {
      // Inflate the menu; this adds items to the action bar if it is present.
      getMenuInflater().inflate(R.menu. main , menu) ;
      return true;
   }
   @Override
   public boolean onOptionsItemSelected (MenuItem item) {
      int id = item.getItemId() ;
      if (id == R.id. action_settings ) {
         return true;
      }
      return super .onOptionsItemSelected(item) ;
   }
   @SuppressWarnings ( "StatementWithEmptyBody" )
   @Override
   public boolean onNavigationItemSelected ( @NonNull MenuItem item) {
      // Handle navigation view item clicks here.
      int id = item.getItemId() ;
      if (id == R.id. nav_camera ) {
         // Handle the camera action
      } else if (id == R.id. nav_gallery ) {
      } else if (id == R.id. nav_slideshow ) {
         } else if (id == R.id. nav_manage ) {
         } else if (id == R.id. nav_share ) {
         } else if (id == R.id. nav_send ) {
      }
      DrawerLayout drawer = findViewById(R.id. drawer_layout ) ;
      drawer.closeDrawer(GravityCompat. START ) ;
      return true;
   }
}

8단계 — 매니페스트 설정

AndroidManifest.xml 파일에 아래 코드를 추가합니다. MainActivity에 NoActionBar 테마를 적용해 커스텀 툴바가 정상적으로 표시되도록 합니다.

<? xml version= "1.0" encoding= "utf-8" ?>
<manifest xmlns: android = "https://schemas.android.com/apk/res/android"
   package= "app.tutorialspoint.com.sample" >
   <application
      android :allowBackup= "true"
      android :icon= "@mipmap/ic_launcher"
      android :label= "@string/app_name"
      android :roundIcon= "@mipmap/ic_launcher_round"
      android :supportsRtl= "true"
      android :theme= "@style/AppTheme" >
      <activity
         android :name= ".MainActivity"
         android :theme= "@style/AppTheme.NoActionBar" >
         <intent-filter>
            <action android :name= "android.intent.action.MAIN" />
            <category android :name= "android.intent.category.LAUNCHER" />
         </intent-filter>
      </activity>
   </application>
</manifest>

앱 실행 및 결과 확인

이제 애플리케이션을 실행해 보겠습니다. 실제 안드로이드 모바일 기기가 컴퓨터에 연결되어 있다고 가정합니다. 안드로이드 스튜디오에서 프로젝트의 액티비티 파일 중 하나를 연 뒤 툴바의 Run(실행) 아이콘을 클릭하고, 옵션 목록에서 본인의 모바일 기기를 선택하세요. 실행이 완료되면 기기 화면에 아래와 같은 기본 화면이 표시됩니다.

안드로이드에서 커스텀 내비게이션 드로어(탐색 창) 만드는 방법