Mobile/Android

[Android] BottomNavigationView를 사용하여 탭 화면 구성을 통해 Fragment 전환하기 - 로아랑(캡스톤 디자인) 프로젝트

n.ooygnas 2022. 12. 13. 16:42

BottomNavigationView

이와 같이 화면 하단에 탭 화면을 구성할 수 있는 뷰이다.

 

탭을 눌러 Fragment를 전환할 수 있으며, 이 프로젝트에서는 5개의 탭으로 구성하였다.

 


activity_main.xml

<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="match_parent"
    android:orientation="vertical">

    <LinearLayout
        android:id="@+id/home_ly"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical"
        android:layout_weight="1"/>

    <com.google.android.material.bottomnavigation.BottomNavigationView
        android:id="@+id/menu_bottom"
        android:layout_width="match_parent"
        android:layout_height="60dp"
        app:menu="@menu/menu_bottom"
        app:itemBackground="@android:color/white"
        app:itemIconTint="@color/selector"
        app:itemTextColor="@color/selector"/>

</LinearLayout>

레이아웃 내부에 Fragment가 보여질 LinearLayout과 BottomNavigationView를 배치했다.

 

 

속성 설명

app:menu="@menu/menu_bottom" 메뉴에 표시될 항목들을 나타내는 속성이다.
나중에 보여줄 menu_bottom.xml에서 항목들을 편집할 수 있다.
app:itemBackground="@android:color/white" 탭 항목의 배경 색을 설정할 수 있는 속성이다.
app:itemIconTint="@color/selector" 탭 항목의 아이콘 색상을 설정할 수 있는 속성이다.
나중에 보여줄 selector.xml에서 색상을 편집할 수 있다.
app:itemTextColor="@color/selector" 탭 항목의 글자 색상을 설정할 수 있는 속성이다.
나중에 보여줄 selector.xml에서 색상을 편집할 수 있다.

 


menu_bottom.xml

<menu xmlns:android="http://schemas.android.com/apk/res/android">

    <item
        android:id="@+id/tab_character"
        android:icon="@drawable/character"
        android:title="캐릭터" />

    <item
        android:id="@+id/tab_homework"
        android:icon="@drawable/homework"
        android:title="주간숙제" />

    <item
        android:id="@+id/tab_calender"
        android:icon="@drawable/calender"
        android:title="일정표" />

    <item
        android:id="@+id/tab_info"
        android:icon="@drawable/info"
        android:title="정보실" />

    <item
        android:id="@+id/tab_setting"
        android:icon="@drawable/setting"
        android:title="설정" />

</menu>

5개 항목에 대한 id 값과 보여질 icon, title을 입력해준다.

 

menu_bottom.xml은 res/menu 폴더에 생성해야 한다.


selector.xml

<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_checked="true" android:color="#53A553"/>
    <item android:color="@color/black"/>
</selector>

activity_main.xml에서 직접 색상을 지정해줘도 되지만,

 

탭 한 항목과 그렇지 않은 항목의 색상을 다르게 하기 위해 selector를 사용하였다.


MainActivity.java

public class MainActivity extends AppCompatActivity {
    LinearLayout home_ly;
    BottomNavigationView bottomNavigationView;

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

        home_ly = findViewById(R.id.home_ly);
        bottomNavigationView = findViewById(R.id.menu_bottom);
        bottomNavigationView.setOnNavigationItemSelectedListener(new TabSelectedListener());
        bottomNavigationView.setSelectedItemId(R.id.tab_character);
    }

    class TabSelectedListener implements BottomNavigationView.OnNavigationItemSelectedListener {
        @Override
        public boolean onNavigationItemSelected(@NonNull MenuItem menuItem) {
            switch (menuItem.getItemId()) {
                case R.id.tab_character: {
                    getSupportFragmentManager().beginTransaction() .replace(R.id.home_ly, new CharacterFragment()) .commit();
                    return true;
                }
                case R.id.tab_homework: {
                    getSupportFragmentManager().beginTransaction() .replace(R.id.home_ly, new HomeworkFragment()) .commit();
                    return true;
                }
                case R.id.tab_calender: {
                    getSupportFragmentManager().beginTransaction() .replace(R.id.home_ly, new CalenderFragment()) .commit();
                    return true;
                }
                case R.id.tab_info: {
                    getSupportFragmentManager().beginTransaction() .replace(R.id.home_ly, new InfoFragment()) .commit();
                    return true;
                }
                case R.id.tab_setting: {
                    getSupportFragmentManager().beginTransaction() .replace(R.id.home_ly, new SettingFragment()) .commit();
                    return true;
                }
            }
            return false;
        }
    }
}

 

bottomNavigationView의 리스너를 설정해주고 기본 선택 아이템을 첫번째 탭으로 설정해주었다.


각 항목의 Fragment를 생성했다고 가정하고 TabSelectedListener에서 선택된 item 항목의 id값을 알아와

 

탭 별로 Fragment를 activity_main.xml의 빈 레이아웃에 replace 시켜주면 탭 화면을 구성할 수 있다.

 


위 내용을 작성하는데 사용된 프로젝트를 깃허브 링크로 첨부합니다.

 

프로젝트의 코드를 참고는 할 수 있으나, 프로젝트 전체를 무단으로 사용하는 행위는 금지합니다.

 

https://github.com/Sangyoon98/Loarang.git

 

GitHub - Sangyoon98/Loarang

Contribute to Sangyoon98/Loarang development by creating an account on GitHub.

github.com