Skip to content

Instantly share code, notes, and snippets.

@girish3
Last active November 11, 2018 05:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save girish3/3bbddd3ba4b38ee75515c2b56045ffff to your computer and use it in GitHub Desktop.
Save girish3/3bbddd3ba4b38ee75515c2b56045ffff to your computer and use it in GitHub Desktop.
[View Pager incomplete, add fragment example] #android_snippet #android

A ViewPager is a ViewGroup that allows the user to flip left and right through pages of data. You supply an implementation of a PagerAdapter to generate the pages that the view shows.

Create a custom Pager Adapter

// override 4 methods as shown below
class MyPagerAdapter: PagerAdapter() {

    override fun instantiateItem(container: ViewGroup, position: Int): Any {

        val inflater = LayoutInflater.from(container.context)
        val view = when {
            position == 0 -> inflater.inflate(R.layout.layout1, container, false)
            position == 1 -> inflater.inflate(R.layout.layout2, container, false)
            position == 2 -> inflater.inflate(R.layout.layout3, container, false)
            else -> {
                inflater.inflate(R.layout.layout1, container, false)
            }
        }
        // add the view to the container
        container.addView(view, 0)
        return view
    }

    override fun isViewFromObject(view: View, `object`: Any): Boolean {
        return view == `object`
    }

    override fun getCount(): Int {
        return 3
    }

    override fun destroyItem(container: ViewGroup, position: Int, `object`: Any) {
        container.removeView(`object` as View)
    }
}

Inside the Activity's onCreate add the adapter to the ViewPager

class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        viewPager.adapter = MyPagerAdapter()
    }
}

Ref:

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment