컴퓨터/android, ios

[Android Kotlin] TabLayout과 ViewPager2를 이용해 화면 구현하기

정석이 2021. 12. 18. 19:04

 

 

앱 롤 백과의 스킨부분을 구현하기 위해

 

 

TabLayout과 ViewPager2를 이용해 옆으로 슬라이드 하거나 tab을 눌렀을 때 화면을 전환할 수 있도록 만들 것이다!

 

 

 

우선 이것만

 

 

 


 

 

 

우선 가장 바깥 틀을 만든다.

 

 

fragment_skin.xml

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout
    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:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".fragment.skin.SkinFragment">

    <androidx.constraintlayout.widget.ConstraintLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <com.google.android.material.tabs.TabLayout
            android:id="@+id/skin_tab_layout"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            app:layout_constraintTop_toTopOf="parent"
            app:layout_constraintLeft_toLeftOf="parent"
            app:layout_constraintRight_toRightOf="parent"/>

        <androidx.viewpager2.widget.ViewPager2
            android:id="@+id/skin_pager"
            android:layout_width="match_parent"
            android:layout_height="0dp"
            android:layoutDirection="ltr"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toBottomOf="@id/skin_tab_layout" />

    </androidx.constraintlayout.widget.ConstraintLayout>

</FrameLayout>

 

 

 

 

 

 

 

 

 

그리고 챔피언별 화면, 스킨 테마별 화면 두 개가 필요한데

 

우선 TextView만 넣어서 화면 전환 확인만 진행할 것이다.

 

 

 

fragment_skin_by_champion.xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 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="match_parent"
        android:gravity="center"
        android:textSize="25sp"
        android:text="챔피언별" />

</androidx.constraintlayout.widget.ConstraintLayout>

 

 

이렇게....

 

 

클래스도 대충 만든다.

 

 

SkinByChampionFragment.kt

package com.example.firstapp.fragment.skin

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.databinding.DataBindingUtil
import androidx.fragment.app.Fragment
import androidx.recyclerview.widget.GridLayoutManager
import com.example.firstapp.R
import com.example.firstapp.adapter.ChampTier.Tier1Adapter
import com.example.firstapp.databinding.FragmentTierTopBinding

class SkinByChampionFragment : Fragment() {
    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {

        return inflater.inflate(R.layout.fragment_skin_by_champion, container, false)

    }
}

 

 

이런식으로! 난 화면을 테마별, 스킨별 일케 2개 구현할거라서 fragment_skin_by_theme도 저거랑 똑같이 넣어줬다.

 

 

 

 

 

 

그리고 ViewPager를 넣을 때 필요한 PagerAdapter를 구현해야한다.

 

 

SkinPagerFragmentAdapter.kt

package com.example.firstapp.adapter.skin

import androidx.fragment.app.Fragment
import androidx.viewpager2.adapter.FragmentStateAdapter
import com.example.firstapp.fragment.skin.SkinByChampionFragment
import com.example.firstapp.fragment.skin.SkinByThemeFragment
import com.example.firstapp.fragment.skin.SkinFragment

class SkinPagerFragmentAdapter(fragmentActivity: SkinFragment) : FragmentStateAdapter(fragmentActivity){
    var fragments : ArrayList<Fragment> = ArrayList()

    override fun getItemCount(): Int {
        return fragments.size
    }

    override fun createFragment(position: Int): Fragment {
        return when(position){
            0 -> SkinByChampionFragment()
            else -> SkinByThemeFragment()
        }
    }


    fun addFragment(fragment: Fragment){
        fragments.add(fragment)
        notifyItemInserted(fragments.size - 1)
    }

    fun removeFragment(){
        fragments.removeLast()
        notifyItemRemoved(fragments.size)
    }

}

 

 

 

 

 

 

 

그리고 tabLayout과 ViewPager를 연결해준다.

 

 

 

SkinFragment.kt

package com.example.firstapp.fragment.skin

import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.viewpager2.widget.ViewPager2
import com.example.firstapp.R
import com.example.firstapp.adapter.skin.SkinPagerFragmentAdapter
import com.google.android.material.tabs.TabLayout
import com.google.android.material.tabs.TabLayoutMediator

class SkinFragment : Fragment() {

    private lateinit var viewPager: ViewPager2
    private lateinit var tabLayout: TabLayout


    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

    }

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        val view:View = inflater.inflate(R.layout.fragment_skin, container, false)
        viewPager = view.findViewById(R.id.skin_pager)
        tabLayout = view.findViewById(R.id.skin_tab_layout)
        return view
    }

    override fun onActivityCreated(savedInstanceState: Bundle?) {
        super.onActivityCreated(savedInstanceState)

        val pagerAdapter = SkinPagerFragmentAdapter(this)

        pagerAdapter.addFragment(SkinByChampionFragment())
        pagerAdapter.addFragment(SkinByThemeFragment())

        viewPager.adapter = pagerAdapter
        viewPager.registerOnPageChangeCallback(object : ViewPager2.OnPageChangeCallback(){
            //이전에 추가된 콜백 제거
            override fun onPageSelected(position: Int) {
                super.onPageSelected(position)
                Log.e("SkinViewPagerFragment", "Page ${position+1}")
            }
        })

        val tabLayoutTextArray = arrayOf("챔피언별", "스킨 테마별")
        TabLayoutMediator(tabLayout, viewPager){ tab, position ->
            tab.text = tabLayoutTextArray[position]
        }.attach()

    }

}

 

 

맨 밑에 TabLayoutMediator를 이용해 tab 이름을 설정하고 viewPager와 연결해준닷