Android App

하단 선택바 (bottomNavigation, Fragment 전환) in Android Studio

YunSeong 2021. 9. 17. 00:05
728x90
반응형

https://youtu.be/stwCk_f3sCw

 

* build.gradle (:app)

https://developer.android.com/reference/com/google/android/material/bottomnavigation/package-summary

 

com.google.android.material.bottomnavigation  |  Android Developers

Content and code samples on this page are subject to the licenses described in the Content License. Java is a registered trademark of Oracle and/or its affiliates. Last updated 2021-07-07 UTC. [{ "type": "thumb-down", "id": "missingTheInformationINeed", "l

developer.android.com

BottomNavigation을 사용하기 위해서는 위 페이지에 있는 라이브러리를 사용해야 한다.

 

이 라이브러리와 연결하기 위해서 

1
2
3
4
5
6
dependencies {
 
            ...     
 
    implementation 'com.google.android.material:material:1.4.0'
}
cs

위와 같이 dependencies에 5열의 text를 입력해줘야 한다.(새로 만든 android Project에 자동으로 입력되어 있을 수도 있다.)


1. bottom_menu.xml (app\src\main\res\menu\ )

1
2
3
4
5
6
7
8
9
10
11
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
 
            ...
 
    <item
        android:id="@+id/action_setting"
        android:enabled="true"
        android:icon="@drawable/ic_baseline_settings_24"
        android:title="airplane"/>
</menu>
cs

6~10 - 위와 같이 item을 원하는 메뉴의 선택지의 개수만큼 등록해준다.


2. activity_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
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 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">
    <FrameLayout
        android:id="@+id/main_frame"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        app:layout_constraintBottom_toTopOf="@+id/bottomNavi"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent">
    </FrameLayout>
    <com.google.android.material.bottomnavigation.BottomNavigationView
        android:id="@+id/bottomNavi"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:itemIconTint="#000000"
        app:itemTextColor="#000000"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:menu="@menu/bottom_menu" />
</androidx.constraintlayout.widget.ConstraintLayout>
cs

8~16 - fragment를 띄울 FrameLayout이다. 

        11, 12, 15 - 위 세 열을 통해서 "Top과 연결된 parent의 Top""Bottom과 연결된 bottomNavi의 Top"까지 꽉 채우도록 FrameLayout의 크기가 조절된다.

 

17~26 - fragment를 전환을 입력 받게 해주는 하단 선택바이다.

        26 - 위에서 등록했었던 bottom_menu.xml을 연결해준다.


3. fragment1.xml

1
2
3
4
5
6
7
8
9
10
11
12
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="1번화면 입니다."
        android:textSize="40sp"
        android:gravity="center"
        android:layout_gravity="center" />
</LinearLayout>
cs

위와 같이 fragment(n).xml선택지의 개수만큼 만든다.


4. Fragment1.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
package com.example.snsappexample;
 
import ...
 
public class Fragment1 extends Fragment {
 
    private View view;
 
    @Nullable
    @org.jetbrains.annotations.Nullable
    @Override
    public View onCreateView(@NonNull @org.jetbrains.annotations.NotNull LayoutInflater inflater, @Nullable @org.jetbrains.annotations.Nullable ViewGroup container, @Nullable @org.jetbrains.annotations.Nullable Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.fragment1, container,  false);
        return view;
    }
}
cs

위와 같이 Fragment(n).java 선택지의 개수만큼 만든다.


5. MainActivity.java

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
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
package com.example.snsappexample;
 
import ...
 
public class MainActivity extends AppCompatActivity {
 
    private BottomNavigationView bottomNavigationView;
    private FragmentManager fragmentManager;
    private FragmentTransaction fragmentTransaction;
    private Fragment1 fragment1;
    private Fragment2 fragment2;
    private Fragment3 fragment3;
    private Fragment4 fragment4;
    private Fragment5 fragment5;
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
 
        bottomNavigationView = findViewById(R.id.bottomNavi);
        fragment1 = new Fragment1();
        fragment2 = new Fragment2();
        fragment3 = new Fragment3();
        fragment4 = new Fragment4();
        fragment5 = new Fragment5();
 
        setFragment(R.id.action_airplane); //제일 처음 띄울 fragment를 설정한다.
 
        bottomNavigationView.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
            @Override
            public boolean onNavigationItemSelected(@NonNull @NotNull MenuItem item) {
                setFragment(item.getItemId()); //item의 id를 인자로 한다.
                return true//true의 의미 = bottomMenu의 애니메이션을 적용시긴다.
            }
        });
    }
 
    private void setFragment(int n){
        fragmentManager = getSupportFragmentManager();
        fragmentTransaction = fragmentManager.beginTransaction();
        switch (n) { //item의 id에 따라서 fragment를 띄우는 각각의 코드를 실행시킨다.
            case R.id.action_airplane :
                fragmentTransaction.replace(R.id.main_frame, fragment1);
                fragmentTransaction.commit();
                break;
            case R.id.action_Bus :
                fragmentTransaction.replace(R.id.main_frame, fragment2);
                fragmentTransaction.commit();
                break;
            case R.id.action_BlueTooth :
                fragmentTransaction.replace(R.id.main_frame, fragment3);
                fragmentTransaction.commit();
                break;
            case R.id.action_create :
                fragmentTransaction.replace(R.id.main_frame, fragment4);
                fragmentTransaction.commit();
                break;
            case R.id.action_setting :
                fragmentTransaction.replace(R.id.main_frame, fragment5);
                fragmentTransaction.commit();
                break;
        }
    }
}
cs

22~26 - 각각의 fragment(n) 변수에 각각의 new Fragment(n)( )로 불러온 fragment 객체를 저장한다.

28 - 맨 처음 띄울 fragment를 설정한다. (setFragment( )함수는 39~64열에서 정의한다.)

30~36 - listener을 통해서 BottomNavigation으로 선택된 item에 접근할 수 있게 해주고 선택될 때의 이벤트를 정의할 수 있다.

        34 - (false를 반환하면 bottomNavigation의 애니메이션이 작동하기 않는 걸로 봐서 작동됐음를 내부적으로 판단하는 용도 같다. 그렇기에 정상적으로 실행 될 때는 true를 아닐 때는 false를 반환해야할 거 같다.)

39~64 매개변수로 받은 item의 id를 이용해서 알맞은 fragmentFrameLayout에 띄우는 역할을 한다.

728x90
반응형