- dependencies 추가

dependencies {
	implementation 'com.google.android.material:material:1.11.0'
}

 

 

- Fragment 클래스 생성  

   : BlankFragment1 / BlankFragment2 / BlankFragment3 동일하게 생성해 준다.

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".BlankFragment1">

    <!-- TODO: Update blank fragment layout -->
    <TextView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:text="@string/hello_blank_fragment" />

</FrameLayout>
package com.example.myapplication;

import android.icu.text.RelativeDateTimeFormatter;
import android.os.Bundle;

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

import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

/**
 * A simple {@link Fragment} subclass.
 * Use the {@link BlankFragment1#newInstance} factory method to
 * create an instance of this fragment.
 */
public class BlankFragment1 extends Fragment {

    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";

    // TODO: Rename and change types of parameters
    private String mParam1;
    private String mParam2;

    public BlankFragment1() {
        // Required empty public constructor
    }

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @param param1 Parameter 1.
     * @param param2 Parameter 2.
     * @return A new instance of fragment BlankFragment1.
     */
    // TODO: Rename and change types and number of parameters
    public static BlankFragment1 newInstance(String param1, String param2) {
        BlankFragment1 fragment = new BlankFragment1();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_blank1, container, false);
    }
}

 

- FragmentAdapter 클래스 생성

class FragmentAdapter extends FragmentStateAdapter {

        private final List<Fragment> mFragmentList = new ArrayList<>();

        public FragmentAdapter(@NonNull FragmentManager fragmentManager, @NonNull Lifecycle lifecycle) {
            super(fragmentManager, lifecycle);
        }

        public void addFragment(Fragment fragment) {
            mFragmentList.add(fragment);
        }

        @NonNull
        @Override
        public Fragment createFragment(int position) {
            return mFragmentList.get(position);
        }

        @Override
        public int getItemCount() {
            return mFragmentList.size();
        }
    }
}

 

 

- activity_fragment

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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"
    android:orientation="vertical"
    tools:context=".FragmentActivity">

    <com.google.android.material.tabs.TabLayout
        android:id="@+id/tabs"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

<!-- 정적 탭아이템 생성 방식-->
<!--        <com.google.android.material.tabs.TabItem-->
<!--            android:layout_width="wrap_content"-->
<!--            android:layout_height="wrap_content"-->
<!--            android:text="첫번째" />-->

<!--        <com.google.android.material.tabs.TabItem-->
<!--            android:layout_width="wrap_content"-->
<!--            android:layout_height="wrap_content"-->
<!--            android:text="두번째" />-->

<!--        <com.google.android.material.tabs.TabItem-->
<!--            android:layout_width="wrap_content"-->
<!--            android:layout_height="wrap_content"-->
<!--            android:text="세번째" />-->
    </com.google.android.material.tabs.TabLayout>

    <androidx.viewpager2.widget.ViewPager2
        android:id="@+id/view_pager"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

</LinearLayout>

 

 

- FragmentActivity 클래스

public class FragmentActivity extends AppCompatActivity {

    private TabLayout tabLayout;
    private ViewPager2 viewPager2;

    private BlankFragment1 blankFragment1;
    private BlankFragment2 blankFragment2;
    private BlankFragment3 blankFragment3;

    private FragmentAdapter adapterFragment;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_fragment);

        tabLayout = findViewById(R.id.tabs);
        viewPager2 = findViewById(R.id.view_pager);

		// Tab item 동적 생성
        TabLayout.Tab oneTab = tabLayout.newTab();
        TabLayout.Tab twoTab = tabLayout.newTab();
        TabLayout.Tab threeTab = tabLayout.newTab();

        oneTab.setText("첫번째");
        twoTab.setText("두번째");
        threeTab.setText("세번째");
        tabLayout.addTab(oneTab);
        tabLayout.addTab(twoTab);
        tabLayout.addTab(threeTab);

		// 페이지뷰에 사용할 Fragment 3페이지 생성
        blankFragment1 = new BlankFragment1();
        blankFragment2 = new BlankFragment2();
        blankFragment3 = new BlankFragment3();

        adapterFragment = new FragmentAdapter(getSupportFragmentManager(), getLifecycle());
        adapterFragment.addFragment(blankFragment1);
        adapterFragment.addFragment(blankFragment2);
        adapterFragment.addFragment(blankFragment3);

        viewPager2.setAdapter(adapterFragment);

        viewPager2.registerOnPageChangeCallback(new ViewPager2.OnPageChangeCallback() {
            @Override
            public void onPageSelected(int position) {
//                super.onPageSelected(position);
                tabLayout.selectTab(tabLayout.getTabAt(position));
            }
        });

        tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                //Tab 버튼 클릭시 ViewPager 화면 이동
                viewPager2.setCurrentItem(tab.getPosition());

                switch (tab.getPosition()) {
                    case 0: break;
                    case 1: break;
                    default: break;
                }
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {

            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {

            }
        });
    }
}

'Android(Java)' 카테고리의 다른 글

[Java]Flagment 기본  (0) 2024.01.16
[Java] Fragment 상호 데이터 전송  (0) 2024.01.16
[Java]Runnable / Lock 동기화 기초  (0) 2024.01.12
[Java] Thread 상속 클래스 타이머 예제  (0) 2024.01.12
[Java] Thread 기본  (0) 2024.01.12

+ Recent posts