-
[안드로이드] ViewPager2와 TabLayout카테고리 없음 2024. 4. 24. 14:27
사용 이유
ViewPager의 개선된 버전이다. 기능 개선과 세로 방향이 추가되었다.
이런 이유 말고도 ViewPager는 더 이상 지원을 하지 않기 때문에 ViewPager2를 사용해야 한다.
사용법
1) Gradle 설정
우선 ViewPager2를 사용하기 위해션 Gradle에 라이브러리를 추가해야 합니다.
dependencies { implementation("androidx.viewpager2:viewpager2:1.0.0") }
2) 각 탭에 사용할 Fragment 생성
class FirstFragment : Fragment() { override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View { val binding = FragmentFirstBinding.inflate(inflater, container, false) return binding.root } }
<!-- fragment_first.xml --> <LinearLayout 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" android:orientation="vertical"> <TextView android:id="@+id/textView" android:layout_width="match_parent" android:layout_height="match_parent" android:gravity="center" android:background="#E53935" android:text="First Fragment" android:textSize="40dp"/> </LinearLayout>
class SecondFragment : Fragment() { override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View { val binding = FragmentSecondBinding.inflate(inflater, container, false) return binding.root } }
<!-- fragment_second.xml --> <LinearLayout 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" android:orientation="vertical"> <TextView android:id="@+id/textView" android:layout_width="match_parent" android:layout_height="match_parent" android:gravity="center" android:background="#E53935" android:text="Second Fragment" android:textSize="40dp"/> </LinearLayout>
3) FragmentStateAdapter를 사용하여 어댑터 클래스 생성
class FragmentAdapter( fragmentManager: FragmentManager, lifecycle: Lifecycle ) : FragmentStateAdapter(fragmentManager, lifecycle) { // 생성자로 필요한 클래스를 받는다 private companion object { const val PAGE_COUNT = 2 } // 여기서 Fragment를 연결해준다 override fun createFragment(position: Int): Fragment { return when (position) { 0 -> FirstFragment() 1 -> SecondFragment() else -> throw NullPointerException("${position}번 Fragment는 존재하지 않습니다.") } } override fun getItemCount(): Int = PAGE_COUNT }
4) MainActivity에 ViewPager와 TabLayout 연결
class SearchActivity : AppCompatActivity() { private companion object { val tabNames = listOf("First", "Second") } private val binding by lazy { ActivityMainBinding.inflate(layoutInflater) } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(binding.root) initView() } private fun initView() = with(binding) { // ViewPager2에 아까 생성한 어댑터를 달아준다. viewPager.adapter = FragmentAdapter(supportFragmentManager, lifecycle) // TabLayout에 ViewPager2를 연결해준다. TabLayoutMediator(tabLayout, viewPager) { tab, position -> tab.text = tabNames[position] }.attach() } }
<?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" android:layout_width="match_parent" android:layout_height="match_parent" android:background="@color/white"> <com.google.android.material.tabs.TabLayout android:id="@+id/tabLayout" android:layout_width="match_parent" android:layout_height="wrap_content" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toTopOf="parent" /> <androidx.viewpager2.widget.ViewPager2 android:id="@+id/viewPager" android:layout_width="match_parent" android:layout_height="0dp" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toBottomOf="@+id/tabLayout" /> </androidx.constraintlayout.widget.ConstraintLayout>
위 코드를 바탕으로 만들어진 앱의 영상이다.
정상적으로 보이는 것을 알 수 있다.