Why Plumbing Must Be Improved To Curb Future Pandemics

In the spring of 2003, 329 people contracted an infectious disease in a high rise building in Hong Kong. 42 of those 329 people lost their lives. The building — Amoy Gardens — was the epicenter of…

Smartphone

独家优惠奖金 100% 高达 1 BTC + 180 免费旋转




Dialogs in Android using Kotlin DSL

To understand how to create DSL in Kotlin you must go and read Part1 first. Now, this article will use learning from the last article to understand how to use Kotlin DSL to simplify Android Dialog API it’s usage.

Let’s just look at what we’re creating before moving forward and build towards it.

This Dialog DSL takes two parameters as inputs namely layoutId and setCustomView.

Now if we look at below DSL from the previous article. You can see in Builder class we define all the properties that we’ll need for our DSL implementation like for above Dialog example: layoutId and setCustomView parameters

Inside the init block of our DSL Builder class we use the properties to implement the logic part. For example, In Dialog DSL we create a MyDialogFragment object and pass layoutId and we initialize a setCustomView callback.

There are two things happening inside this DialogFragment. One we’re inflating the view using the layoutId we received.

Second, we initialize and invoke setCustomView callback with these parameters (inflated view + dialog reference) in this callback.

We have implemented DSL methods in the DSL builder class inside the companion block.

Just to be clear this block is the code block inside {} braces of Dialog DSL example above which we use to initialize Builder class using apply keyword.

In Android, we have to create a new Dialog class every time we want to show a dialog and then we’ll have to pass the data as parameters and implement an Interface to receive callbacks. I didn’t like this whole process and came up with this simple DSL solution.

With DSLs we can use Dialogs or BottomSheetDialogs just like any other views in our projects, not to forget we don’t have to copy-paste code every time we have to create a new Dialog.

Thanks for reading this article. Be sure to 👏 recommend this article if you found it helpful. It means a lot.

Add a comment

Related posts:

Think You Are Immune To Burnout? Here Is Why So Many People Are Burning Out

As I help organizations improve employee wellbeing, I often find myself in conversations about the trends that contribute to the rise in burnout. This article is my attempt to uncover the leading…

A Very Short Story About Hunger

He moved across the room, hunger and passion fueling each stride before he reached her. Her eyes fixed on him, she didn’t know what was coming, but she felt his energy his power and his want and…

Buy Glassdoor Reviews

Do you want to know what your employees think of you? Then you can check out employee rating websites like Glassdoor; You may be surprised. In today’s competitive job market, you will not be able to…