DBILITY

안드로이드 TabLayout + ViewPager2 + Fragment swipe 본문

android/kotlin

안드로이드 TabLayout + ViewPager2 + Fragment swipe

DBILITY 2024. 3. 21. 17:46
반응형

https://hyperrookie.tistory.com/741

 

안드로이드 ViewPager2 + Fragment swape

ViewPager2를 사용해 fragement swape를 구현해 봤다. 핵심은 ViewPager2에 FragmentStateAdapter를 구현하는 것이다. PageAdapter.kt package com.example.myviewpager2fragment.adapter import androidx.fragment.app.Fragment import androidx.fragm

dbility.com

직전에 했던 코드에 TabLayout을 추가했다.

TabItem의 title용 array가 필요하고 ViewPage2 adapter를 연결한 후에 다음과 같이 처리

TabLayoutMediator(tabLayout, activityMainViewPager2) { tab, position ->
    tab.text = tabTitles[position]
}.attach()

MainActivity.kt

package com.example.myviewpager2fragment

import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.util.Log
import android.view.View
import android.widget.Toast
import androidx.activity.OnBackPressedCallback
import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import androidx.fragment.app.Fragment
import androidx.viewpager2.widget.ViewPager2.OnPageChangeCallback
import com.example.myviewpager2fragment.adapter.PageAdapter
import com.example.myviewpager2fragment.databinding.ActivityMainBinding
import com.example.myviewpager2fragment.fragment.FirstFragment
import com.example.myviewpager2fragment.fragment.SecondFragment
import com.google.android.material.tabs.TabLayoutMediator
import kotlin.system.exitProcess

class MainActivity : AppCompatActivity() {

    private val binding by lazy {
        ActivityMainBinding.inflate(layoutInflater)
    }
    private lateinit var pageAdapter: PageAdapter
    private lateinit var tabTitles: MutableList<String>
    private lateinit var fragmentList: MutableList<Fragment>
    private lateinit var firstFragment: FirstFragment
    private lateinit var secondFragment: SecondFragment
    private var isTerminated: Boolean = false

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        enableEdgeToEdge()
        setContentView(binding.root)
        ViewCompat.setOnApplyWindowInsetsListener(binding.main) { v, insets ->
            val systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars())
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom)
            insets
        }

        this.onBackPressedDispatcher.addCallback(this, object : OnBackPressedCallback(true) {
            override fun handleOnBackPressed() {
                if (binding.activityMainViewPager2.currentItem == 0) {
                    if (!isTerminated) {
                        Toast.makeText(this@MainActivity, "한번 더 클릭하면 종료됩니다", Toast.LENGTH_SHORT)
                            .show()
                    } else {
                        Handler(mainLooper).postDelayed({
                            finishAndRemoveTask()
                            exitProcess(0)
                        }, 100)
                    }
                } else {
                    binding.activityMainViewPager2.currentItem -= 1
                }
            }
        })

        tabTitles = mutableListOf("First", "Second")
        firstFragment = FirstFragment(binding)
        secondFragment = SecondFragment()
        fragmentList = mutableListOf(firstFragment, secondFragment)

        pageAdapter = PageAdapter(this, fragmentList)

        with(binding) {

            activityMainViewPager2.apply {
                adapter = pageAdapter
                registerOnPageChangeCallback(object : OnPageChangeCallback() {
                    override fun onPageSelected(position: Int) {
                        super.onPageSelected(position)
                        activityMainImageButtonBack.visibility =
                            if (position == 0) View.INVISIBLE else View.VISIBLE
                    }
                })
            }

            TabLayoutMediator(tabLayout, activityMainViewPager2) { tab, position ->
                tab.text = tabTitles[position]
            }.attach()

            activityMainImageButtonBack.setOnClickListener {
                if (activityMainViewPager2.currentItem == 1) {
                    activityMainViewPager2.currentItem = 0
                }
            }
        }
    }
}

반응형
Comments