Android TabLayout ViewPager2

passΒ·2023λ…„ 7μ›” 10일
1

Android

λͺ©λ‘ 보기
15/41

πŸ”₯ TabLayout κ³Ό ViewPager λ₯Ό μ‚¬μš©ν•˜μ—¬ μŠ€μ™€μ΄ν”„ νŽ˜μ΄μ§€ κ΅¬ν˜„ν•˜κΈ°

🎈 TabLayout κ³Ό ViewPager 에 λŒ€ν•΄ μ•Œμ•„λ³΄κ³ , TabLayout κ³Ό ViewPager2 λ₯Ό μ‚¬μš©ν•˜μ—¬ μŠ€μ™€μ΄ν”„ νŽ˜μ΄μ§€λ₯Ό κ΅¬ν˜„ν•œ 예제λ₯Ό μ‚΄νŽ΄λ³΄μž.


TabLayout 은 Anroid μ—μ„œ μ‚¬μš©μžκ°€ νƒ­ ν˜•μ‹μœΌλ‘œ λ‹€λ₯Έ νƒ­ κ°„μ˜ μ „ν™˜μ„ ν•  수 μžˆλŠ” UI μ»΄ν¬λ„ŒνŠΈμ΄λ‹€. 주둜 μ•±μ˜ μƒλ‹¨μ΄λ‚˜ ν•˜λ‹¨μ—μ„œ λ„€λΉ„κ²Œμ΄μ…˜ λ°”λ‘œ μ‚¬μš©λ˜λ©°, 탭을 ν„°μΉ˜ν•˜λ©΄ ν•΄λ‹Ή μ„Ήμ…˜μ˜ 탭이 보여진닀.
ViewPager λŠ” Android μ—μ„œ μŠ€μ™€μ΄ν”„ 기반의 νŽ˜μ΄μ§€ μ „ν™˜μ„ μ œκ³΅ν•˜λŠ” UI μ»΄ν¬λ„ŒνŠΈμ΄λ‹€.

TabLayout κ³Ό ViewPager λ₯Ό ν•¨κ»˜ μ μš©ν•˜λ©΄ 탭을 ν„°μΉ˜ν•˜μ—¬ 화면을 μ „ν™˜ν•˜λŠ” κ²ƒλΏλ§Œ μ•„λ‹ˆλΌ μŠ€μ™€μ΄ν”„λ₯Ό ν†΅ν•˜μ—¬ 화면을 μ „ν™˜ν•  수 μžˆλ‹€.




🌈 Anroid Studio ν”„λ‘œμ νŠΈ 생성 기본적으둜 μ œκ³΅ν•˜κ³  μžˆλŠ” Layout 쀑 TabLayout 을 μ‚΄νŽ΄λ³΄μž.


βœ” activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.coordinatorlayout.widget.CoordinatorLayout 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"
    tools:context=".MainActivity">

    <com.google.android.material.appbar.AppBarLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:theme="@style/Theme.PracticeTabActivity.AppBarOverlay">

        <TextView
            android:id="@+id/title"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:gravity="center"
            android:minHeight="?actionBarSize"
            android:padding="@dimen/appbar_padding"
            android:text="@string/app_name"
            android:textAppearance="@style/TextAppearance.Widget.AppCompat.Toolbar.Title" />

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

    <androidx.viewpager.widget.ViewPager
        android:id="@+id/view_pager"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:layout_behavior="@string/appbar_scrolling_view_behavior" />

    <com.google.android.material.floatingactionbutton.FloatingActionButton
        android:id="@+id/fab"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="bottom|end"
        android:layout_marginEnd="@dimen/fab_margin"
        android:layout_marginBottom="16dp"
        app:srcCompat="@android:drawable/ic_dialog_email" />
</androidx.coordinatorlayout.widget.CoordinatorLayout>
  • TabLayout κ³Ό ViewPager λ₯Ό μž‘μ„±



βœ” fragment_main.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"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/constraintLayout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".ui.main.PlaceholderFragment">

    <TextView
        android:id="@+id/section_label"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="@dimen/activity_horizontal_margin"
        android:layout_marginTop="@dimen/activity_vertical_margin"
        android:layout_marginEnd="@dimen/activity_horizontal_margin"
        android:layout_marginBottom="@dimen/activity_vertical_margin"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintTop_toTopOf="@+id/constraintLayout"
        tools:layout_constraintLeft_creator="1"
        tools:layout_constraintTop_creator="1" />

</androidx.constraintlayout.widget.ConstraintLayout>



βœ” MainActivity.kt

class MainActivity : AppCompatActivity() {

    private lateinit var binding: ActivityMainBinding

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

        binding = ActivityMainBinding.inflate(layoutInflater)
        setContentView(binding.root)

        val sectionsPagerAdapter = SectionsPagerAdapter(this, supportFragmentManager)
        val viewPager: ViewPager = binding.viewPager
        viewPager.adapter = sectionsPagerAdapter
        val tabs: TabLayout = binding.tabs
        tabs.setupWithViewPager(viewPager)
        val fab: FloatingActionButton = binding.fab

        fab.setOnClickListener { view ->
            Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
                .setAction("Action", null).show()
        }
    }
}
  • ViewPager에 Adapter μ…‹νŒ…
  • TabLayout에 ViewPager μ…‹νŒ…



βœ” SectionsPagerAdapter.kt

class SectionsPagerAdapter(private val context: Context, fm: FragmentManager) :
    FragmentPagerAdapter(fm) {

    override fun getItem(position: Int): Fragment {
        // getItem is called to instantiate the fragment for the given page.
        // Return a PlaceholderFragment (defined as a static inner class below).
        return PlaceholderFragment.newInstance(position + 1)
    }

    override fun getPageTitle(position: Int): CharSequence? {
        return context.resources.getString(TAB_TITLES[position])
    }

    override fun getCount(): Int {
        // Show 2 total pages.
        return 2
    }
}     



PlaceholderFragment.kt

class PlaceholderFragment : Fragment() {

    private lateinit var pageViewModel: PageViewModel
    private var _binding: FragmentMainBinding? = null

    // This property is only valid between onCreateView and
    // onDestroyView.
    private val binding get() = _binding!!

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        pageViewModel = ViewModelProvider(this).get(PageViewModel::class.java).apply {
            setIndex(arguments?.getInt(ARG_SECTION_NUMBER) ?: 1)
        }
    }

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

        _binding = FragmentMainBinding.inflate(inflater, container, false)
        val root = binding.root

        val textView: TextView = binding.sectionLabel
        pageViewModel.text.observe(viewLifecycleOwner, Observer {
            textView.text = it
        })
        return root
    }

    companion object {
        /**
         * The fragment argument representing the section number for this
         * fragment.
         */
        private const val ARG_SECTION_NUMBER = "section_number"

        /**
         * Returns a new instance of this fragment for the given section
         * number.
         */
        @JvmStatic
        fun newInstance(sectionNumber: Int): PlaceholderFragment {
            return PlaceholderFragment().apply {
                arguments = Bundle().apply {
                    putInt(ARG_SECTION_NUMBER, sectionNumber)
                }
            }
        }
    }

    override fun onDestroyView() {
        super.onDestroyView()
        _binding = null
    }
}



profile
μ•ˆλ“œλ‘œμ΄λ“œ 개발자 지망생

0개의 λŒ“κΈ€