본문 바로가기
안드로이드/Material-Design

Android Material Design 따라하기 7 - Fragment & Adapter

by 프로나인 2020. 11. 1.

안녕하세요 프로나인 입니다.

이제 가을이 오면서 날씨가 슬슬 쌀쌀해지고 있는데 건강 관리 잘하시면서 독감과 코로나도 조심하시기 바랍니다☺️

 

koohee.tistory.com/17

 

Android Material Design 따라하기 6 - BottomNavigation

안녕하세요 프로나인입니다. 내일부터 길다면 길고 짧다면 짧은 추석 명절이 시작되는데요. 코로나 조심하시고 명절도 잘 보내시길 바랍니다! 😄 koohee.tistory.com/16 Android Material Design 따라하기 5

koohee.tistory.com

지난 시간에 이어 BottomNavigation을 클릭 시 활용될 Fragment를 만들어 보도록 하겠습니다.


Fragment 화면

우선 앞 시간에 bottomnavigation.xml에서 FrameLayout을 지정해줬습니다.

저희는 이제 이 FrameLayout에 들어갈 화면들을 만들어 볼 것입니다.

BottomNavigation에 메뉴가 3개니 각각 들어갈 화면도 3개를 만들어보겠습니다.

 

<bottomnavi_fragment_1.xml>

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

    <TextView
        android:id="@+id/tv_fragment"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="PAGE = 1"
        android:textSize="32sp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>

 

<bottomnavi_fragment_2.xml>

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

    <TextView
        android:id="@+id/tv_fragment"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="PAGE = 2"
        android:textSize="32sp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>

 

<bottomnavi_fragment_3.xml>

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

    <TextView
        android:id="@+id/tv_fragment"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="PAGE = 3"
        android:textSize="32sp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>

각각 화면의 내용은 자기의 입맛에 맞춰서 바꾸시면 됩니다!

 

이렇게 만든 화면을 코드로 연결을 해줘야 되겠죠!?

package 각자 패키지명 ;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

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

저는 클래스명을 Menu_BottomNavi_Fragment_1 로 지어 줬습니다. 이런 식으로 2번째 화면 , 3번째 화면 이어주면 됩니다!

Fragment 연결

이제 각각 Fragment의 화면을 BottomNavigation을 클릭할 때마다 화면이 바뀌도록 연결을 시켜주겠습니다.

package 패키지명;

import android.os.Bundle;
import android.view.MenuItem;
import android.widget.FrameLayout;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;

import com.google.android.material.bottomnavigation.BottomNavigationView;

public class Menu_BottomNavigation extends AppCompatActivity {
    FrameLayout frameLayout;
    BottomNavigationView bottomNavigationView;
    FragmentManager fragmentManager;
    FragmentTransaction fragmentTransaction;

    Menu_BottomNavi_Fragment_1 menu_bottomNavi_fragment_1 = new Menu_BottomNavi_Fragment_1();
    Menu_BottomNavi_Fragment_2 menu_bottomNavi_fragment_2 = new Menu_BottomNavi_Fragment_2();
    Menu_BottomNavi_Fragment_3 menu_bottomNavi_fragment_3 = new Menu_BottomNavi_Fragment_3();

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

        bottomNavigationView = (BottomNavigationView) findViewById(R.id.bottomnavi);
        frameLayout = (FrameLayout) findViewById(R.id.framelayout);
        fragmentManager = getSupportFragmentManager();
        fragmentTransaction = fragmentManager.beginTransaction();
        fragmentTransaction.addR.id.framelayout,menu_bottomNavi_fragment_1);
        fragmentTransaction.addToBackStack(null);
        fragmentTransaction.commit();

        bottomNavigationView.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
            @Override
            public boolean onNavigationItemSelected(@NonNull MenuItem item) {
                changeFragment(item.getItemId());
                return true;
            }
        });
    }
    public void changeFragment(int title_id) {
        fragmentTransaction = fragmentManager.beginTransaction();

        switch (title_id) {
            case R.id.bottomnavi_one :
                fragmentTransaction.replace(R.id.framelayout,menu_bottomNavi_fragment_1);
                fragmentTransaction.commit();
                break;
            case R.id.bottomnavi_two :
                fragmentTransaction.replace(R.id.framelayout,menu_bottomNavi_fragment_2);
                fragmentTransaction.commit();
                break;
            case R.id.bottomnavi_three :
                fragmentTransaction.replace(R.id.framelayout,menu_bottomNavi_fragment_3);
                fragmentTransaction.commit();
                break;
        }
        return;
    }

}

 

코드가 상당히 길어 보이지만 분석해보시면 상당히 쉽습니다.😄

  bottomNavigationView = (BottomNavigationView) findViewById(R.id.bottomnavi);
  frameLayout = (FrameLayout) findViewById(R.id.framelayout);
  fragmentManager = getSupportFragmentManager();
  fragmentTransaction = fragmentManager.beginTransaction();
  fragmentTransaction.add(R.id.framelayout,menu_bottomNavi_fragment_1);
  fragmentTransaction.commit();

1. fragmentManager를 선언

2. fragmentTransaction을 선언

3. fragmentTransaction.add로 최초 fragment를 add 해줍니다. (해당 activity로 진입을 할 때 보일 화면)

4. commit을 해주면 fragmentTransaction에 add 한 fragment 가 붙습니다! 

 

이어서 BottomNavigation을 클릭 이벤트로 fragment를 replace 하도록 해보겠습니다.

 bottomNavigationView.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
            @Override
            public boolean onNavigationItemSelected(@NonNull MenuItem item) {
                changeFragment(item.getItemId());
                return true;
            }
        });

저는 가독성을 좀 높여 보기 위해 changeFragment라는 메서드를 만들어 클릭 시 해당 Id값을 전달해주도록 했습니다.

 

아 그리고 여기서 중요한 점!👊

return 이 true 냐 false 내에 차이가 있습니다. 

true면 클릭 시 해당 부분이 클릭됐다는 표시 (진하기, 색변화) 같이 적용이 될 수 있고,

false는 클릭시 해당 부분이 변화가 없습니다. 

 

이런 부분에는 차후에 Fragment에 게시글을 작성하여 아주 세세하게 파헤쳐 보도록 하겠습니다!

 

public void changeFragment(int title_id) {
        fragmentTransaction = fragmentManager.beginTransaction();

        switch (title_id) {
            case R.id.bottomnavi_one :
                fragmentTransaction.replace(R.id.framelayout,menu_bottomNavi_fragment_1);
                fragmentTransaction.commit();
                break;
            case R.id.bottomnavi_two :
                fragmentTransaction.replace(R.id.framelayout,menu_bottomNavi_fragment_2);
                fragmentTransaction.commit();
                break;
            case R.id.bottomnavi_three :
                fragmentTransaction.replace(R.id.framelayout,menu_bottomNavi_fragment_3);
                fragmentTransaction.commit();
                break;
        }
        return;
    }

changeFragment 메서드입니다.

보시면 저는 switch 구문으로 만들었습니다! 이게 꼭 정답은 아니에요 단지 저는 이게 더 가독성에 있어서 편해서 했을 뿐😄

각자 코딩 스타일에 따라 작성하시면 됩니다.

여기서도 중요한 점! 👊

fragmentTransaction.add 가 아닌 replace를 사용하여 commit을 해주는 점입니다.

add (프레그먼트 추가)  replace (프레그먼트 교체)  remove (프레그먼트 삭제)

이런 느낌으로 생각해주시면 됩니다.


결과

결과 화면입니다. 가운데 Fragment 화면이 바뀌는 것을 확인할 수 있고,

하단 BottomNavigation을 클릭할 때마다 색이 바뀌는 것을 확인할 수 있습니다! 

 

 

 


참조 - 안드로이드 Developer (Fragment) 

developer.android.com/guide/components/fragments?hl=ko

 

프래그먼트  |  Android 개발자  |  Android Developers

A Fragment represents a behavior or a portion of user interface in an Activity. You can combine multiple fragments in a single activity to build a multi-pane UI and reuse a fragment in multiple activities. You can think of a fragment as a modular section

developer.android.com

참조 - Material Design

https://material.io/develop/android/

 

Material Design

Build beautiful, usable products faster. Material Design is an adaptable system—backed by open-source code—that helps teams build high quality digital experiences.

material.io

 

댓글