간단하게 이미지 슬라이드를 만들어보려고 함!
ViewPager를 사용하기 위해서는 dependencies에 아래 코드를 추가해줘야 함
implementation ("androidx.viewpager2:viewpager2:1.0.0")
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<androidx.viewpager2.widget.ViewPager2
android:id="@+id/viewPager"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</RelativeLayout>
이미지 표시를 위한 레이아웃
<?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">
<ImageView
android:id="@+id/imageView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:adjustViewBounds="true"
android:scaleType="centerCrop"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
class MainActivity : AppCompatActivity() {
private lateinit var viewPager: ViewPager2
private val images = listOf(
R.drawable.image1,
R.drawable.image2,
R.drawable.image3
)
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
viewPager = findViewById(R.id.viewPager)
val adapter = ImageAdapter(images)
viewPager.adapter = adapter
}
}
ViewPager에서 이미지를 표시하는 데 사용할 어댑터
class ImageAdapter(private val images: List<Int>) : RecyclerView.Adapter<ImageAdapter.ImageViewHolder>() {
inner class ImageViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
val imageView: ImageView = itemView.findViewById(R.id.imageView)
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ImageViewHolder {
val itemView = LayoutInflater.from(parent.context).inflate(R.layout.item_image, parent, false)
return ImageViewHolder(itemView)
}
override fun onBindViewHolder(holder: ImageViewHolder, position: Int) {
val imageResource = images[position]
holder.imageView.setImageResource(imageResource)
}
override fun getItemCount(): Int {
return images.size
}
}
[참고 사이트]
'ViewPager2', Develpers
'ViewPager2 samples', Android(GitHub)
'ViewPager2를 사용하여 탭으로 스와이프 뷰 만들기', Developers