Skip to content

Instantly share code, notes, and snippets.

@soulduse
Created July 13, 2018 09:35
Show Gist options
  • Save soulduse/4be6057b49b4c612728cd22329348487 to your computer and use it in GitHub Desktop.
Save soulduse/4be6057b49b4c612728cd22329348487 to your computer and use it in GitHub Desktop.
class DynamicImageView: LinearLayout {
private var imagesPath = mutableListOf<String>()
private val horizontalLayoutParam by lazy { LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT) }
private val weightZeroLayoutParam by lazy { LinearLayout.LayoutParams(0, 380, 1F) }
constructor(context: Context) : super(context)
fun addImage(vararg path: String) : DynamicImageView {
path.forEach {
imagesPath.add(it)
}
return this
}
fun show() : DynamicImageView {
val imageSize = imagesPath.size
when(imageSize) {
0 -> { } // Nothing
in 1 .. 3 -> { addSingleLinearLayout(imageSize) }
else -> { addTwiceLinearLayout(imageSize) } // imageSize > 3
}
return this
}
private fun addSingleLinearLayout(position: Int) {
val linear = getHorizontalLinearLayout()
(0 until position)
.map { getImageView(it) }
.forEach { linear.addView(it) }
this.addView(linear)
}
private fun addTwiceLinearLayout(position: Int) {
val linearContainer = getVerticalLinearLayout()
if(position == 4) {
val topLineLinearLayout = getHorizontalLinearLayout().apply {
addView(getImageView(0))
addView(getImageView(1))
}
val bottomLineLinearLayout = getHorizontalLinearLayout().apply {
addView(getImageView(2))
addView(getImageView(3))
}
linearContainer.addView(topLineLinearLayout)
linearContainer.addView(bottomLineLinearLayout)
} else {
val topLinearLayout = getHorizontalLinearLayout()
val bottomLineLinearLayout = getHorizontalLinearLayout()
(0 until 3)
.map { getImageView(it) }
.forEach { topLinearLayout.addView(it) }
(3 until position)
.map { getImageView(it) }
.forEach { bottomLineLinearLayout.addView(it) }
linearContainer.addView(topLinearLayout)
linearContainer.addView(bottomLineLinearLayout)
}
this.addView(linearContainer)
}
private fun getHorizontalLinearLayout(): LinearLayout {
return LinearLayout(context).apply {
orientation = LinearLayout.HORIZONTAL
layoutParams = horizontalLayoutParam
}
}
private fun getVerticalLinearLayout(): LinearLayout {
return LinearLayout(context).apply {
orientation = LinearLayout.VERTICAL
layoutParams = horizontalLayoutParam
}
}
private fun getImageView(position: Int): ImageView {
val image = ImageView(context).apply {
layoutParams = weightZeroLayoutParam
scaleType = ImageView.ScaleType.FIT_XY
}
Log.w("DynamicImageView", "position: $position, image: ${imagesPath[position]}")
GlideApp.with(context)
.load(imagesPath[position])
.into(image)
return image
}
}