ABOUT ME

dddd-

Today
-
Yesterday
-
Total
-
  • [BottomNavigationView] 안드로이드 BottomNavigationView 사용하기
    Android/개발 2018. 10. 27. 18:50


    안드로이드 BottomNavigationView 사용하기







    예전 안드로이드 앱들은 왼쪽상단에 햄버거 버튼을 두고 버튼을 누르면 좌측에서 Drawer가 나와 메뉴가 표시되는 UI를 많이 사용했습니다. 시간이 지나면서 BottomNavigationView를 많이 사용하는데 UI/UX면에서 사용자에게 훨씬 편하고 직관적이기 때문입니다. 오늘은 따라하기만 하면 완성되는 BottomNavigationView 만들기를 알아보도록 하겠습니다!


    // 많이들 착각하시는 것이 BottomNavigationView를 Bottom Tab이라고 하시며 TabLayout 대신 사용하시는 분들이 있는데 완전 틀린말은 아니지만 Tab과 Navigation에는 역할적으로 많은 차이가 있습니다. 앞서 햄버거 버튼대신 많이 사용한다고고 말씀 드렸는데 그것의 이름이 NavigationDrawer라는 것을 보면 알 수 있습니다. 구글에서도 BottomNavigationView에는 TabLayout과 달리 Swipe해서 화면을 넘기는것을 권장하지 않고 있죠. 나중에 시간이 된다면 Tab과 Navigation의 차이로 글을 써보겠습니다. 

    BottomNavigationView 공식 가이드 라인확인하기 






    구현 방법은 build.gradle 작성, menu 파일 작성, activity xml 파일 작성, fragment xml, java 파일 작성, activity java 파일 작성 5단계로 이루어지며 한단계씩 따라하시면 금방 만들어보실 수 있습니다!



    1. build.gradle(Module: app)파일 수정


    implementation 'com.android.support:design:27.1.1'


    - BottomNavigationView는 design support library로 사용합니다.





    2. BottomNavigationView에 들어갈 menu_bottom.xml 파일 작성

     2-1) [res에서 마우스 오른쪽 버튼] - [New] - [Android Resource Directory]

     2-2) Resource Type: menu - [OK]

     2-3) [res의 menu에서 마우스 오른쪽 버튼] - [New] - [Menu resource file]

     2-4) file name 지정 - [OK] // 여기선 menu_bottom

     2-5) menu_bottom.xml 파일 작성

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

    <item
    android:id="@+id/navigation_menu1"
    android:icon="@android:drawable/ic_menu_call"
    android:title="MENU1" />

    <item
    android:id="@+id/navigation_menu2"
    android:icon="@android:drawable/ic_menu_camera"
    android:title="MENU2" />

    <item
    android:id="@+id/navigation_menu3"
    android:icon="@android:drawable/ic_menu_edit"
    android:title="MENU3" />

    <item
    android:id="@+id/navigation_menu4"
    android:icon="@android:drawable/ic_menu_help"
    android:title="MENU3" />

    </menu>


    - 최소 3개 ~ 최대 5개 권장(구글)






    3. activity_main.xml 파일 수정

    <?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"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <!-- 각각의 Fragment를 넣을 Container -->
    <FrameLayout
    android:id="@+id/frame_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_marginBottom="?attr/actionBarSize"/>

    <android.support.design.widget.BottomNavigationView
    android:id="@+id/bottom_navigation_view"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_gravity="bottom"
    android:background="?android:attr/windowBackground"
    app:menu="@menu/menu_bottom"/>
    </android.support.design.widget.CoordinatorLayout>


    - BottomNavigationViewapp:menu 속성에 방금 만든 menu_bottom파일을 넣어줍니다.





    4. fragment_menu.xml과 MenuFragment.java 파일 작성

    fragment_menu1.xml

    <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent">

    <TextView
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center"
    android:text="MENU 1"/>
    </LinearLayout>

    Menu1Fragment.java

    package com.imaec.forblog;

    import android.os.Bundle;
    import android.support.annotation.NonNull;
    import android.support.annotation.Nullable;
    import android.support.v4.app.Fragment;
    import android.view.LayoutInflater;
    import android.view.View;
    import android.view.ViewGroup;

    public class Menu1Fragment extends Fragment {

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
    return inflater.inflate(R.layout.fragment_menu1, container, false);
    }
    }


    - 이 예제에선 간단히 TextView 하나만 만들어 놓았습니다.

      그리고 Menu를 4개 사용할 것이기 때문에 위의 4번을 3번더 반복하여 fragment_menu2, fragment_menu3, fragment_menu4 xml 파일과 Menu2Fragment, Menu3Fragment, Menu4Fragment java 파일을 만들어 줍니다.






    5. MainActivity.java 파일 수정

    package com.imaec.forblog;

    import android.support.annotation.NonNull;
    import android.support.design.widget.BottomNavigationView;
    import android.support.v4.app.FragmentManager;
    import android.support.v4.app.FragmentTransaction;
    import android.support.v7.app.AppCompatActivity;
    import android.os.Bundle;
    import android.view.MenuItem;

    public class MainActivity extends AppCompatActivity {

    // FrameLayout에 각 메뉴의 Fragment를 바꿔 줌
    private FragmentManager fragmentManager = getSupportFragmentManager();
    // 4개의 메뉴에 들어갈 Fragment들
    private Menu1Fragment menu1Fragment = new Menu1Fragment();
    private Menu2Fragment menu2Fragment = new Menu2Fragment();
    private Menu3Fragment menu3Fragment = new Menu3Fragment();
    private Menu4Fragment menu4Fragment = new Menu4Fragment();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    BottomNavigationView bottomNavigationView = findViewById(R.id.bottom_navigation_view);
    // 첫 화면 지정
    FragmentTransaction transaction = fragmentManager.beginTransaction();
    transaction.replace(R.id.frame_layout, menu1Fragment).commitAllowingStateLoss();

    // bottomNavigationView의 아이템이 선택될 때 호출될 리스너 등록
    bottomNavigationView.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
    @Override
    public boolean onNavigationItemSelected(@NonNull MenuItem item) {
    FragmentTransaction transaction = fragmentManager.beginTransaction();
    switch (item.getItemId()) {
    case R.id.navigation_menu1: {
    transaction.replace(R.id.frame_layout, menu1Fragment).commitAllowingStateLoss();
    break;
    }
    case R.id.navigation_menu2: {
    transaction.replace(R.id.frame_layout, menu2Fragment).commitAllowingStateLoss();
    break;
    }
    case R.id.navigation_menu3: {
    transaction.replace(R.id.frame_layout, menu3Fragment).commitAllowingStateLoss();
    break;
    }
    case R.id.navigation_menu4: {
    transaction.replace(R.id.frame_layout, menu4Fragment).commitAllowingStateLoss();
    break;
    }
    }

    return true;
    }
    });
    }
    }


    - 완성되었습니다! 결과를 확인해 볼까요






    결과


    - 간단하게 BottomNavigationView를 만들었습니다!

    결과 스크린샷을 보면 메뉴가 선택될 때마다 탭들의 위치가 고정되어있지 않고 조금씩 움직이는 것을 볼 수 있습니다. 이것을 BottomNavigationViewShiftMode가 켜져있기 때문인데 이 모드를 끄는 방법은 아래 글에서 확인해주세요!

    (세번째 메뉴와 네번째 메뉴의 이름이 MENU3으로 같은것은 단순 오타입니다..ㅎ)


    안드로이드 BottomNavigationView를 이용한 프로젝트 구경하기

    BottomNavigationView ShiftMode 끄기



    * 궁금한점이 있으시면 댓글로 남겨주세요~ 최대한 빨리 답변드리도록 하겠습니다!





    댓글

Designed by Tistory.