画像をスクロールする系のチュートリアル画面をViewPagerを使って実装します。🚀
本来のチュートリアルだと完了ボタンやIndicatorがあると思いますが、とりあえず画像をスクロールするだけの基本実装です。
MainActivity.kt
package com.shanonim.viewpagersample
import android.databinding.DataBindingUtil
import android.os.Bundle
import android.support.v7.app.AppCompatActivity
import com.shanonim.viewpagersample.databinding.ActivityMainBinding
class MainActivity : AppCompatActivity() {
lateinit private var binding: ActivityMainBinding
private val images: IntArray = intArrayOf(
R.drawable.tutorial_01,
R.drawable.tutorial_02,
R.drawable.tutorial_03,
R.drawable.tutorial_04,
R.drawable.tutorial_05
)
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = DataBindingUtil.setContentView(this, R.layout.activity_main)
binding.viewPager.adapter = CustomPagerAdapter(this, images)
}
}
CustomPagerAdapter.kt
package com.shanonim.viewpagersample
import android.content.Context
import android.support.v4.view.PagerAdapter
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.LinearLayout
import com.shanonim.viewpagersample.databinding.ItemTutorialBinding
class CustomPagerAdapter(val context: Context, val images: IntArray) : PagerAdapter() {
override fun getCount(): Int = images.size
override fun isViewFromObject(view: View?, `object`: Any?): Boolean {
return view == `object`
}
override fun instantiateItem(container: ViewGroup?, position: Int): Any {
val binding = ItemTutorialBinding.inflate(LayoutInflater.from(context), container, false)
binding.imageView.setImageResource(images[position])
container?.addView(binding.root)
return binding.root
}
override fun destroyItem(container: ViewGroup?, position: Int, `object`: Any?) {
container?.removeView(`object` as LinearLayout)
}
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.shanonim.viewpagersample.MainActivity">
<android.support.v4.view.ViewPager
android:id="@+id/view_pager"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</RelativeLayout>
</layout>
item_view_pager.xml
<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<ImageView
android:id="@+id/image_view"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
</layout>
まとめ
- Kotlin最高🎉
参考サイト
- Android Image Slider Using ViewPager Example
http://www.thecrazyprogrammer.com/2016/12/android-image-slider-using-viewpager-example.html