안드로이드

[Android] 탭 메뉴의 구현 (TabLayout과 ViewPager2)

IT꿈나무 2021. 7. 14. 18:19
반응형

*업무의 목적:

 플레이스토어 처럼 상위에 탭 메뉴를 구현한다. 이 기능을 구현하기 위해서는 ViewPager2와 TabLayout을 이용해서 구현할수 있다.

 

 

관련코드:

1. activity_main.xml

<?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=".MainActivity">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hello World!"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintHorizontal_bias="0.047"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.022" />
    <com.google.android.material.tabs.TabLayout
        android:id="@+id/layout_tab"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        app:tabGravity="center"
        app:tabMode="scrollable"
        app:tabTextColor="#000000"
        app:tabSelectedTextColor="#FF0000"
        app:tabIndicatorColor="#00FF00" />

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

2. ContentsPagerAdapter.java

package com.example.storetabbar1;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import androidx.viewpager2.adapter.FragmentStateAdapter;

import org.jetbrains.annotations.NotNull;

public class ContentsPagerAdapter extends FragmentStateAdapter {
    private int mPageCount = 5;


    public ContentsPagerAdapter(AppCompatActivity fm) {
        super(fm);
        //this.mPageCount = pageCount;
    }

    @NonNull
    @NotNull
    @Override
    public Fragment createFragment(int position) {
        switch (position) {

            case 0:
                BlankFragment01 blankFragment01 = new BlankFragment01();
                return blankFragment01;
            case 1:
                BlankFragment02 blankFragment02 = new BlankFragment02();
                return blankFragment02;
            case 2:
                BlankFragment03 blankFragment03 = new BlankFragment03();
                return blankFragment03;
            case 3:
                BlankFragment01 blankFragment04 = new BlankFragment01();
                return blankFragment04;
            case 4:
                BlankFragment02 blankFragment05 = new BlankFragment02();
                return blankFragment05;
            case 5:
                BlankFragment03 blankFragment06 = new BlankFragment03();
                return blankFragment06;

            default:
                return null;
        }
    }

    @Override
    public long getItemId(int position) {
        return super.getItemId(position);
    }

    @Override
    public int getItemCount() {
        return mPageCount;
    }
}

3. MainActivity

package com.example.storetabbar1;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.viewpager2.widget.ViewPager2;

import android.os.Bundle;
import android.widget.TextView;

import com.google.android.material.tabs.TabLayout;
import com.google.android.material.tabs.TabLayoutMediator;

import org.jetbrains.annotations.NotNull;

import java.util.Arrays;
import java.util.List;

public class MainActivity extends AppCompatActivity {

    private TabLayout mTabLayout;

    private ViewPager2 mViewPager;
    private ContentsPagerAdapter mContentPagerAdapter;

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

        mTabLayout = (TabLayout) findViewById(R.id.layout_tab);
//        mTabLayout.addTab(mTabLayout.newTab().setText("홈"));
        
        mViewPager = (ViewPager2) findViewById(R.id.pager_content);

        //프레그먼트 이동 구현
        ContentsPagerAdapter contentsPagerAdapter = new ContentsPagerAdapter(this);
        mViewPager.setAdapter(contentsPagerAdapter);

        final List<String> tabElement = Arrays.asList("홈","게임","ㅅㅁㅅ","ㅇㄹㅇㄹㅇㄹ","ㅇㄹㅇㄹㅇㄹㅇ","ㅇㄹㅇㄹㅇㄹㅇ");

        //tabLyout와 viewPager 연결
        new TabLayoutMediator(mTabLayout, mViewPager, new TabLayoutMediator.TabConfigurationStrategy() {
            @Override
            public void onConfigureTab(@NonNull @NotNull TabLayout.Tab tab, int position) {
                TextView textView = new TextView(MainActivity.this);
                textView.setText(tabElement.get(position));
                tab.setCustomView(textView);
            }
        }).attach();


    }
}

프로젝트 첨부:

storeTabBar1.7z
0.46MB

 

참고자료:

[1] [Android] TabLayout과 ViewPager, https://re-build.tistory.com/25

[2] viewPager2 활용 예제, https://todaycode.tistory.com/27?category=979455

[3] TabLayout과 viewPager2 연결 하기, https://huiveloper.tistory.com/10

[4] !! 뷰페이저에 인디케이터 달기, https://bacassf.tistory.com/106

[5] 뷰페이저 인디케이터 라이브러리, https://github.com/tommybuonomo/dotsindicator?utm_source=android-arsenal.com&utm_medium=referral&utm_campaign=7127 , https://velog.io/@l2hyunwoo/Android-기능-구현-2

 

 

반응형