chinwag-android/app/src/main/java/com/keylesspalace/tusky/pager/ImagePagerAdapter.kt

43 lines
1.7 KiB
Kotlin
Raw Normal View History

package com.keylesspalace.tusky.pager
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentActivity
import com.keylesspalace.tusky.ViewMediaAdapter
import com.keylesspalace.tusky.entity.Attachment
import com.keylesspalace.tusky.fragment.ViewMediaFragment
import java.lang.ref.WeakReference
class ImagePagerAdapter(
activity: FragmentActivity,
private val attachments: List<Attachment>,
private val initialPosition: Int
) : ViewMediaAdapter(activity) {
2019-08-18 04:05:24 +10:00
private var didTransition = false
private val fragments = MutableList<WeakReference<ViewMediaFragment>?>(attachments.size) { null }
override fun getItemCount() = attachments.size
override fun createFragment(position: Int): Fragment {
if (position >= 0 && position < attachments.size) {
2019-08-18 04:05:24 +10:00
// Fragment should not wait for or start transition if it already happened but we
// instantiate the same fragment again, e.g. open the first photo, scroll to the
// forth photo and then back to the first. The first fragment will try to start the
2019-08-18 04:05:24 +10:00
// transition and wait until it's over and it will never take place.
val fragment = ViewMediaFragment.newInstance(
2019-08-18 04:05:24 +10:00
attachment = attachments[position],
shouldStartPostponedTransition = !didTransition && position == initialPosition
)
fragments[position] = WeakReference(fragment)
return fragment
} else {
throw IllegalStateException()
}
}
override fun onTransitionEnd(position: Int) {
2019-08-18 04:05:24 +10:00
this.didTransition = true
fragments[position]?.get()?.onTransitionEnd()
}
}