ViewPager2
ViewPager2는 ViewPager 라이브러리의 개선된 버전입니다.
다음은 ViewPager2의 새로운 기능입니다.
- RecyclerView를 기반으로 사용
- 수직 스크롤링 지원 (기존에는 좌우 스크롤링만 가능)
- notifyDataSetChanged 기능
- 페이지 변경 애니메이션 제어 기능 향상
- 사용하기 편해진 페이지 변경 리스너
ViewPager2 구현하기
1. build.gradle에 의존성 추가
ViewPager2을 사용하기 위해서 build.gradle에 ViewPager2 라이브러리를 추가합니다.
implementation 'androidx.viewpager2:viewpager2:1.0.0'
2. 레이아웃에 ViewPager2 추가
ViewPager2를 추가하는 동시에 몇 번째 항목을 나타내는지 표시하기 위한 TabLayout을 추가합니다.
<?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/viewPager"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_marginBottom="50dp"
app:layout_constraintBottom_toBottomOf="@+id/tabLayout"
app:layout_constraintTop_toTopOf="parent" />
<com.google.android.material.tabs.TabLayout
android:id="@+id/tabLayout"
android:paddingHorizontal="12dp"
android:layout_width="wrap_content"
android:layout_height="50dp"
app:tabIndicator="@null"
app:tabBackground="@drawable/selector_tab"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintBottom_toBottomOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
3. ViewPager2에 들어갈 이미지 레이아웃 제작
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageView
android:id="@+id/iv_item"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</LinearLayout>
4. TabLayout을 이용한 Indicator 만들기
Tab Indicator에서 현재 선택된 항목에 대해서는 ic_dot_selected가 적용되고 선택되지 않은 항목에 대해서는 ic_dot_unselected가 적용됩니다.

<!-- selector_tab.xml -->
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="@drawable/ic_dot_selected" android:state_selected="true" />
<item android:drawable="@drawable/ic_dot_unselected" android:state_selected="false" />
</selector>
<!-- ic_dot_selected.xml -->
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:innerRadius="0dp"
android:shape="ring"
android:thickness="3dp"
android:useLevel="false">
<solid android:color="@color/black" />
</shape>
<!-- ic_dot_unselected.xml -->
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:innerRadius="0dp"
android:shape="ring"
android:thickness="3dp"
android:useLevel="false">
<solid android:color="@color/gray" />
</shape>
5. Adapter 설정
ViewPager2는 RecyclerView를 기반으로 하기 때문에 사용법이 같습니다.
class ItemAdapter(private val list : List<ImageItem>) :
RecyclerView.Adapter<ItemAdapter.ItemViewHolder>() {
data class ImageItem(val uri: Uri)
inner class ItemViewHolder(private val binding: ItemImageBinding) : RecyclerView.ViewHolder(binding.root) {
fun bind(item: ImageItem) {
binding.ivItem.setImageURI(item.uri)
}
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ItemViewHolder {
val inflater = parent.context.getSystemService(Context.LAYOUT_INFLATER_SERVICE) as LayoutInflater
val binding = ItemFrameBinding.inflate(inflater, parent, false)
return ItemViewHolder(binding)
}
override fun onBindViewHolder(holder: ItemViewHolder, position: Int) {
holder.bind(list[position])
}
override fun getItemCount() = list.size
}
6. 만들어놓은 Indicator와 Adpater에 ViewPager2 연결
// Intent로 받은 정보를 ImageAdapter.ImageItem에 매핑시켜 저장
val images = (intent.getStringArrayExtra("images") ?: emptyArray())
.map { uriString -> ImageAdapter.ImageItem(Uri.parse(uriString)) }
// Adapter 연결
binding.viewPager.adapter = ImageAdapter(images)
// Indicator 연결
TabLayoutMediator(binding.tabLayout, binding.viewPager) { tab, _ ->
binding.viewPager.currentItem = tab.position
}.attach()
728x90
반응형
'안드로이드 > 활용' 카테고리의 다른 글
[Android] Socket 통신 (0) | 2023.08.17 |
---|---|
[Android] MediaPlayer와 MediaRecoder (0) | 2023.08.02 |
[Android] ListAdapter로 RecyclerView 효율적으로 사용하기 (0) | 2023.07.27 |
[Android] RecyclerView (0) | 2023.07.26 |
[Android] addView와 ListView (0) | 2023.07.25 |
ViewPager2
ViewPager2는 ViewPager 라이브러리의 개선된 버전입니다.
다음은 ViewPager2의 새로운 기능입니다.
- RecyclerView를 기반으로 사용
- 수직 스크롤링 지원 (기존에는 좌우 스크롤링만 가능)
- notifyDataSetChanged 기능
- 페이지 변경 애니메이션 제어 기능 향상
- 사용하기 편해진 페이지 변경 리스너
ViewPager2 구현하기
1. build.gradle에 의존성 추가
ViewPager2을 사용하기 위해서 build.gradle에 ViewPager2 라이브러리를 추가합니다.
implementation 'androidx.viewpager2:viewpager2:1.0.0'
2. 레이아웃에 ViewPager2 추가
ViewPager2를 추가하는 동시에 몇 번째 항목을 나타내는지 표시하기 위한 TabLayout을 추가합니다.
<?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/viewPager" android:layout_width="match_parent" android:layout_height="0dp" android:layout_marginBottom="50dp" app:layout_constraintBottom_toBottomOf="@+id/tabLayout" app:layout_constraintTop_toTopOf="parent" /> <com.google.android.material.tabs.TabLayout android:id="@+id/tabLayout" android:paddingHorizontal="12dp" android:layout_width="wrap_content" android:layout_height="50dp" app:tabIndicator="@null" app:tabBackground="@drawable/selector_tab" app:layout_constraintStart_toStartOf="parent" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintBottom_toBottomOf="parent" /> </androidx.constraintlayout.widget.ConstraintLayout>
3. ViewPager2에 들어갈 이미지 레이아웃 제작
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent"> <ImageView android:id="@+id/iv_item" android:layout_width="match_parent" android:layout_height="match_parent"/> </LinearLayout>
4. TabLayout을 이용한 Indicator 만들기
Tab Indicator에서 현재 선택된 항목에 대해서는 ic_dot_selected가 적용되고 선택되지 않은 항목에 대해서는 ic_dot_unselected가 적용됩니다.

<!-- selector_tab.xml --> <?xml version="1.0" encoding="utf-8"?> <selector xmlns:android="http://schemas.android.com/apk/res/android"> <item android:drawable="@drawable/ic_dot_selected" android:state_selected="true" /> <item android:drawable="@drawable/ic_dot_unselected" android:state_selected="false" /> </selector> <!-- ic_dot_selected.xml --> <?xml version="1.0" encoding="utf-8"?> <shape xmlns:android="http://schemas.android.com/apk/res/android" android:innerRadius="0dp" android:shape="ring" android:thickness="3dp" android:useLevel="false"> <solid android:color="@color/black" /> </shape> <!-- ic_dot_unselected.xml --> <?xml version="1.0" encoding="utf-8"?> <shape xmlns:android="http://schemas.android.com/apk/res/android" android:innerRadius="0dp" android:shape="ring" android:thickness="3dp" android:useLevel="false"> <solid android:color="@color/gray" /> </shape>
5. Adapter 설정
ViewPager2는 RecyclerView를 기반으로 하기 때문에 사용법이 같습니다.
class ItemAdapter(private val list : List<ImageItem>) : RecyclerView.Adapter<ItemAdapter.ItemViewHolder>() { data class ImageItem(val uri: Uri) inner class ItemViewHolder(private val binding: ItemImageBinding) : RecyclerView.ViewHolder(binding.root) { fun bind(item: ImageItem) { binding.ivItem.setImageURI(item.uri) } } override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ItemViewHolder { val inflater = parent.context.getSystemService(Context.LAYOUT_INFLATER_SERVICE) as LayoutInflater val binding = ItemFrameBinding.inflate(inflater, parent, false) return ItemViewHolder(binding) } override fun onBindViewHolder(holder: ItemViewHolder, position: Int) { holder.bind(list[position]) } override fun getItemCount() = list.size }
6. 만들어놓은 Indicator와 Adpater에 ViewPager2 연결
// Intent로 받은 정보를 ImageAdapter.ImageItem에 매핑시켜 저장 val images = (intent.getStringArrayExtra("images") ?: emptyArray()) .map { uriString -> ImageAdapter.ImageItem(Uri.parse(uriString)) } // Adapter 연결 binding.viewPager.adapter = ImageAdapter(images) // Indicator 연결 TabLayoutMediator(binding.tabLayout, binding.viewPager) { tab, _ -> binding.viewPager.currentItem = tab.position }.attach()
728x90
반응형
'안드로이드 > 활용' 카테고리의 다른 글
[Android] Socket 통신 (0) | 2023.08.17 |
---|---|
[Android] MediaPlayer와 MediaRecoder (0) | 2023.08.02 |
[Android] ListAdapter로 RecyclerView 효율적으로 사용하기 (0) | 2023.07.27 |
[Android] RecyclerView (0) | 2023.07.26 |
[Android] addView와 ListView (0) | 2023.07.25 |