Last active
November 15, 2023 07:38
-
-
Save mirokolodii/173744d00ea6e7a5e082f289df840a26 to your computer and use it in GitHub Desktop.
Android custom view
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class OrderView @JvmOverloads constructor( | |
context: Context, | |
attrs: AttributeSet? = null | |
) : ConstraintLayout(context, attrs) { | |
private val binding = ViewOrderBinding.inflate(LayoutInflater.from(context), this) | |
init { | |
setPadding(context.dpToPx(16)) | |
background = context.drawable(R.drawable.background_info_view) | |
} | |
fun init(status: Status, items: Map<String, String>) { | |
initItems(items) | |
initLabel(status) | |
initButton(status) | |
} | |
private fun initItems(items: Map<String, String>) { | |
var topViewId = binding.title.id | |
items.forEach { item -> | |
val textView = TextView(context).apply { | |
id = generateViewId() | |
text = context.getString(string.item_description, item.key, item.value) | |
setTextColor(context.color(R.color.primary)) | |
setTextAppearance(R.style.TextNormal) | |
} | |
addView(textView) | |
setConstraints(view = textView, topViewId = topViewId) | |
topViewId = id | |
} | |
} | |
private fun initLabel(status: Status) { | |
@StringRes val text: Int | |
@ColorRes val backgroundColorRes: Int | |
@DrawableRes val iconRes: Int | |
when (status) { | |
DRAFT -> { | |
text = string.draft | |
backgroundColorRes = R.color.draft | |
iconRes = R.drawable.ic_line_circle | |
} | |
IN_PROGRESS -> { | |
text = string.in_progress | |
backgroundColorRes = R.color.in_progress | |
iconRes = R.drawable.ic_arrow_circle_right | |
} | |
COMPLETE -> { | |
text = string.complete | |
backgroundColorRes = R.color.complete | |
iconRes = R.drawable.ic_check_circle | |
} | |
} | |
binding.apply { | |
label.text = context.getString(text) | |
label.backgroundTintList = ColorStateList.valueOf(context.color(backgroundColorRes)) | |
label.setCompoundDrawablesWithIntrinsicBounds(iconRes, 0, 0, 0) | |
} | |
} | |
private fun initButton(status: Status) = when (status) { | |
DRAFT -> binding.button.text = context.getString(string.create) | |
IN_PROGRESS -> binding.button.text = context.getString(string.open) | |
COMPLETE -> binding.button.isVisible = false | |
} | |
private fun setConstraints(view: View, topViewId: Int) { | |
val constraintSet = ConstraintSet().apply { | |
clone(this@OrderView) | |
connect(view.id, ConstraintSet.START, ConstraintSet.PARENT_ID, ConstraintSet.START) | |
connect(view.id, ConstraintSet.TOP, topViewId, ConstraintSet.BOTTOM, context.dpToPx(8)) | |
} | |
constraintSet.applyTo(this) | |
} | |
} | |
enum class Status { | |
DRAFT, IN_PROGRESS, COMPLETE | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment