Log.v(“ThreeTips”, “#16”)

Mert SIMSEK
2 min readNov 20, 2017

1 — @BindingAdapter and Kotlin

@BindingAdapter is maybe the most powerful feature of databinding library in android world. It allows you to create your custom attribute. To see an example to usage, you can check 2.tip in log #10 . In java, we used to create @BindingAdapter just like that;

public class BindingTextUtils {

@BindingAdapter({"imageUrl"})
public static void loadImage(ImageView v, String url) {
Picasso.with(view.getContext()).load(url).into(view)
}
}

But, in kotlin it is a bit different. I though that I can just change static method to companion object.

class BindingAdapterUtils {

companion object {

@BindingAdapter(value = "imageUrl")
fun load(view: ImageView, url: String) = Picasso.with(view.context).load(url).into(view)
}
}

But sorry, that will not work. To make it work, you need to remove class and companion object scope and use the method in the file.

@BindingAdapter(value = "imageUrl")
fun load(view: ImageView, url: String) = Picasso.with(view.context).load(url).into(view)

2 — Dagger 2 + Kotlin = Be Aware of Wildcards

Kotlin generates our code to work with java. Sometimes it generates the code that we don’t want. In my case, Dagger 2 multibinding and Kotlin didn’t like each other in first sight. But I mediated.

If you don’t want to kotlin generates your code with wildcards, you need to use @JvmSuppressWildcards.

If you want to provide your ViewModel using ViewModelFactory and using dagger 2 multibinding. You need to use method like that;

3 — Where do those attributes belong?

Styles are good. It is making the look and feel of our application UI more consistent. But sometimes we all use it wrong. I will explain a little why it is wrong.

Let’s say we created a Button style and put width, height, gravity, color and elevation attribute to styles. Then we use that style in the xml. Everything works great. UI is as expected. But we created another screen and used same style in new xml. But we want bigger button in new page. So do we have to create another style for that? No. So we should remove width and height attributes out and put them in xml.

We can think the same for other attributes. Gravity? Gravity is not supported for all container views. So also gravity is not belong to styles. For making a decision about which attributes belong to where, we should ask this question: “Can I use this style anywhere else if needed?”. If “NO” then refactor you style.

Quick rule from Sebastiano

You put the layout attributes in the layout, and everything else in the styles!

--

--