본문 바로가기
Develop/Android

세로 방향 뷰페이저 적용하기 - Vertical ViewPager (Kotlin)

by 라이프레이서 2019. 12. 22.
반응형

1. 전환될 때 효과 설정

class DefaultTransformer : ViewPager.PageTransformer {
    override fun transformPage(view: View, position: Float) {
        var alpha = 0f
        if (0 <= position && position <= 1) {
            alpha = 1 - position     //position은 페이지 이동할때마다 -1부터0 또는 0부터 1 값 가짐
        } else if (-1 < position && position < 0) {
            alpha = position + 1
        }
        view.alpha = alpha
        view.translationX = view.width * -position//이전에 그려져 있던 뷰와 시작점이 같도록 설정해주는 것
        //위 부분 설정하지 않으면 오른쪽 끝점을 기준으로 새로운 뷰가 그려진다.
        val yPosition = position * view.height
        view.translationY = yPosition//뷰의 맨 아래를 기준으로 새로운 뷰를 그리도록 함.
        //설정하지 않으면 이전에 그렸던 뷰의 윗부분이 시작점이 되어 뷰가 그려지게 됨
    }
}

 

2. 세로 방향 뷰페이저 만들기

class VerticalViewPager @JvmOverloads constructor(
    context: Context?,
    attrs: AttributeSet? = null
) :
    ViewPager(context!!, attrs) {
    private fun swapTouchEvent(event: MotionEvent): MotionEvent {
        val width: Float = getWidth().toFloat()
        val height: Float = getHeight().toFloat()
        val swappedX = event.y / height * width
        val swappedY = event.x / width * height
        event.setLocation(swappedX, swappedY)
        return event//위아래로 스크롤시 페이지 전환 일어나도록 하는 부분
    }

    override fun onInterceptTouchEvent(event: MotionEvent): Boolean {
        val intercept: Boolean = super.onInterceptTouchEvent(swapTouchEvent(event))
        //If not intercept, touch event should not be swapped.
        swapTouchEvent(event)
        return intercept
    }

    override fun onTouchEvent(ev: MotionEvent): Boolean {
        return super.onTouchEvent(swapTouchEvent(ev))
    }

    init {
        setPageTransformer(false, DefaultTransformer())
    }
}

3. 레이아웃 구성

<!--activity_main.xml-->
<?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">

    <kr.chjdevelop.verticalviewpager.VerticalViewPager
        android:id="@+id/viewPager"
        android:layout_width="match_parent"
        android:layout_height="match_parent"/>

</androidx.constraintlayout.widget.ConstraintLayout>
<!--item.xml-->
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:id="@+id/ll_item"
    android:layout_height="match_parent">

</LinearLayout>

 

4. 데이터 클래스 만들어주기

data class PageItem(
    val text : String
)

5. 어댑터 만들어주기

class MainPagerAdapter(private val context : Context) : PagerAdapter(){
    val datas = mutableListOf<PageItem>()
    override fun isViewFromObject(view: View, `object`: Any): Boolean {
        return view == `object`
    }

    fun addItem(item : PageItem){
        datas.add(item)
    }

    override fun getCount(): Int {
        return datas.size
    }

    override fun instantiateItem(container: ViewGroup, position: Int): Any {
        val view : View = LayoutInflater.from(container.context).inflate(R.layout.item,container,false)
        container.addView(view)
        bind(datas.get(position),view)
        return view
    }
    private fun bind(textItem : PageItem,view : View){
        val ll_item = view.findViewById<LinearLayout>(R.id.ll_item)
        when(textItem.text){
            "1" -> {ll_item.setBackgroundColor(ContextCompat.getColor(context,R.color.colorPastelPink))}
            "2" -> {ll_item.setBackgroundColor(ContextCompat.getColor(context,R.color.colorRym))}
            "3" -> {ll_item.setBackgroundColor(ContextCompat.getColor(context,R.color.colorSky))}
            "4" -> {ll_item.setBackgroundColor(ContextCompat.getColor(context,R.color.colorPrimary))}
        }
    }
}

6. 적용

class MainActivity : AppCompatActivity() {
    lateinit var adapter : MainPagerAdapter

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        init()
    }
    private fun init(){
        adapter = MainPagerAdapter(this)
        adapter.addItem(PageItem("1"))
        adapter.addItem(PageItem("2"))
        adapter.addItem(PageItem("3"))
        adapter.addItem(PageItem("4"))
        viewPager.adapter = adapter
        viewPager.setPageTransformer(false,DefaultTransformer())
        viewPager.offscreenPageLimit=3
    }
}

 

 

 

<실행 화면>

반응형