Skip to content

Instantly share code, notes, and snippets.

@ntngel1
Created November 14, 2019 14:43
Show Gist options
  • Save ntngel1/25f2a4844753de1ac848d94f006eb891 to your computer and use it in GitHub Desktop.
Save ntngel1/25f2a4844753de1ac848d94f006eb891 to your computer and use it in GitHub Desktop.
class FullscreenImagesDialogFragment : DialogFragment() {
sealed class Params {
@Parcelize
data class Images(
val images: List<String>,
val offset: Int = 0
) : Params(), Parcelable
@Parcelize
data class Image(
val image: String,
val title: String = ""
) : Params(), Parcelable
}
private val params by argument<Params>(PARAMS_KEY)
init {
setStyle(STYLE_NO_TITLE, android.R.style.Theme_Black_NoTitleBar)
}
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
return inflater.inflate(R.layout.dialog_fullscreen_images, container, false)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
setupToolbar()
setupImagesRecyclerView()
}
private fun setupToolbar() {
params.let { params ->
toolbar.title = when (params) {
is Params.Images -> str(R.string.imageFormat, params.offset + 1)
is Params.Image -> params.title
}
}
toolbar.setNavigationOnClickListener { dismiss() }
toolbar.setNavigationIcon(R.drawable.ic_arrow_back_white_24dp)
}
private fun setupImagesRecyclerView() {
imagesRecyclerView.layoutManager =
LinearLayoutManager(context, LinearLayoutManager.HORIZONTAL, false)
PagerSnapHelper().attachToRecyclerView(imagesRecyclerView)
params.let { params ->
when (params) {
is Params.Images -> {
initRecyclerViewWithImages(params)
}
is Params.Image -> {
initRecyclerViewWithImage(params)
}
}
}
}
private fun initRecyclerViewWithImage(params: Params.Image) {
val adapter = FullscreenImageAdapter()
adapter.images = listOf(params.image)
imagesRecyclerView.adapter = adapter
}
private fun initRecyclerViewWithImages(params: Params.Images) {
val adapter = FullscreenImageAdapter()
adapter.images = params.images
val scrollListener = FullscreenImagesScrollListener { currentPosition ->
toolbar.title = str(R.string.imageFormat, currentPosition + 1)
}
imagesRecyclerView.adapter = adapter
imagesRecyclerView.addOnScrollListener(scrollListener)
imagesRecyclerView.scrollToPosition(params.offset)
}
companion object {
private const val PARAMS_KEY = "params"
fun newInstance(params: Params) = FullscreenImagesDialogFragment().apply {
arguments = bundleOf(PARAMS_KEY to params)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment