Creating reusable AlertDialogs with Custom Views in Anko

Moyinoluwa Adeyemi
Apr 30, 2018 · 3 min read

AlertDialog with default layout

implementation "org.jetbrains.anko:anko-commons:$anko_version"
alert {
titleResource = R.string.title
messageResource = R.string.message
positiveButton(R.string.ok, { dialog ->
dialog.dismiss()
})
negativeButton(R.string.cancel, { dialog ->
dialog.dismiss()
})
show()
}

Reusable AlertDialog with a Custom View

Sample dialog
implementation "org.jetbrains.anko:anko-appcompat-v7:$anko_version"
implementation "org.jetbrains.anko:anko-sdk25:$anko_version"
class FeedbackDialog(ui: AnkoContext<View>) {

lateinit var dialog: DialogInterface
lateinit var feedbackText: TextInputEditText
lateinit var cancelButton: TextView
lateinit var okButton: TextView

init {
with(ui) {
dialog = alert {
customView {
verticalLayout {
padding = dip(16)

textView(R.string.some_title) { ... }

textView(R.string.some_message) { ... }

textInputLayout {
hint = context.getString(R.string.hint)
feedbackText = textInputEditText {
textSize = 16f
}
}

// More DSL goes here
}
}
}
.show()
}
}
}
class MainActivity : AppCompatActivity() {

override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
}

private fun displayFeedbackDialog(view: View) {
val feedbackDialogUi by lazy {
contentView
?.let {
FeedbackDialog
(AnkoContext.create(ctx, it))
}
}

feedbackDialogUi?.okButton?.setOnClickListener {
val text = feedbackDialogUi.feedbackText.text.toString()
toast(getString(R.string.confirmation, text))

feedbackDialogUi.dialog.dismiss()
}

feedbackDialogUi?.cancelButton?.setOnClickListener {
feedbackDialogUi.dialog.dismiss()
}
}
}

Conclusion

Moyinoluwa Adeyemi

Written by

Android Dev @OffGridE, Marathoner

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade