Skip to content

Instantly share code, notes, and snippets.

@nosix
Last active July 26, 2016 14:07
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 nosix/c4e49fa941cc92e4bd966c7a939cc8a6 to your computer and use it in GitHub Desktop.
Save nosix/c4e49fa941cc92e4bd966c7a939cc8a6 to your computer and use it in GitHub Desktop.
ViewPager for Android (SDK 22) in Kotlin 1.0.2. It can be scrolled in one direction. (Left only, Right only or Both)
<?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">
<xxx.view.CustomViewPager
android:id="@+id/main_container"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</RelativeLayout>
package xxx.view
import android.content.Context
import android.support.v4.view.ViewPager
import android.util.AttributeSet
import android.view.MotionEvent
class CustomViewPager(context: Context, attrs: AttributeSet?) : ViewPager(context, attrs) {
constructor(context: Context) : this(context, null)
companion object {
val SCROLL_PREV = 0b01 // Left
val SCROLL_NEXT = 0b10 // Right
val SCROLL_BOTH = SCROLL_NEXT + SCROLL_PREV
}
var scrollDirection = SCROLL_BOTH
private var downX: Float? = null
override fun onTouchEvent(ev: MotionEvent): Boolean =
if (canScroll(ev)) super.onTouchEvent(ev) else false
override fun onInterceptTouchEvent(ev: MotionEvent): Boolean =
if (canScroll(ev)) super.onInterceptTouchEvent(ev) else false
private fun canScroll(ev: MotionEvent): Boolean {
if (ev.action == MotionEvent.ACTION_DOWN) {
downX = ev.x
return true
}
downX?.let {
val diffX = ev.x - it
if (diffX > 0 && scrollDirection.and(SCROLL_PREV) == 0) {
return false
}
if (diffX < 0 && scrollDirection.and(SCROLL_NEXT) == 0) {
return false
}
}
return true
}
}
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
findViewById(R.id.main_container).let {
it as CustomViewPager
it.scrollDirection = CustomViewPager.SCROLL_PREV
it.adapter = MainPagerAdapter(supportFragmentManager) // Plaese implement MainPagerAdapter
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment