화면 슬라이드 기능을 구현하는 데 사용되는 위젯 중 하나로 ViewPager와 비교해서 개선된 버전이다.
ViewPager2는 아이템 어탭터를 사용하여 각 화면의 콘텐츠를 관리. RecyclerView.Adapter와 유사하며 ViewPager2에 표시할 데이터와 뷰를 관리한다.(DiffUtil를 통한 뷰 재활용 가능)
수평 및 수직 슬라이드를 모두 지원.
notifyDataSetChanged 문제 해결.
implementation 'androidx.viewpager2:viewpager2:1.0.0'
<?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:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<androidx.viewpager2.widget.ViewPager2
android:id="@+id/viewPager2"
android:layout_width="match_parent"
android:layout_height="0dp"
app:layout_constraintBottom_toTopOf="@+id/tapLayout"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<com.google.android.material.tabs.TabLayout
android:id="@+id/tapLayout"
android:layout_width="match_parent"
android:layout_height="50dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
class SearchFragment : Fragment() {
private lateinit var binding: FragmentSearchBinding
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
binding = FragmentSearchBinding.inflate(inflater, container, false)
return binding.root
}
}
@LikeFragment
class LikeFragment : Fragment() {
private lateinit var binding: FragmentLikeBinding
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
binding = FragmentLikeBinding.inflate(inflater, container, false)
return binding.root
}
}
4.ViewPager2 어댑터 설정
class ViewPagerAdapter (fragmentActivity: FragmentActivity) : FragmentStateAdapter(fragmentActivity){
private var fragments: ArrayList<Fragment> = arrayListOf(SearchFragment(), LikeFragment())
override fun getItemCount(): Int {
return fragments.size
}
override fun createFragment(position: Int): Fragment {
return fragments[position]
}
}
class MainActivity : AppCompatActivity() {
private val binding by lazy {ActivityMainBinding.inflate(layoutInflater)}
private val tabTextList = listOf("검색결과", "내 보관함")
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(binding.root)
binding.viewPager2.adapter = ViewPagerAdapter(this)
TabLayoutMediator(binding.tapLayout, binding.viewPager2) { tab, pos ->
tab.text = tabTextList[pos]
}.attach()
}
}