Any way to change names for auto-created views by kotlin-extensions?

Viewed 513

I'm new in Kotlin. I've red https://kotlinlang.org/docs/tutorials/android-plugin.html and noticed that views can be auto-binded to activity via importing kotlinx.android.synthetic.main.activity_main.*.

If I declaring view with id = "btn_login" in Activity I can access to it via

activity.btn_login.setText("Login")

But. Is there any way to change alias to view, such as ButterKnife does :

@BindView(<id of view>)
<name of view>
2 Answers

It's a synthetic import, so technically you can use an import alias to call it by another name:

import kotlinx.android.synthetic.main.activity_main.view.btn_login as btnLogin

But considering there is no tool that does this automatically, you might want to just embrace a different ID naming scheme.

Here's a reasonable one:

What-Where-Description-Modifier:

recyclerSearchSuggestions - RecyclerView showing search suggestions

fabSearchGo - FloatingActionButton that executes a search

textSearchFilterChip - TextView that represents search filters, styled as a material chip

buttonSearchClearFilter - Button that clears selected filter chips

editSearchFilter - EditText used to narrow down search suggestions

The only way you can, as far as I know, is by using named imports. This is a really nice feature of the Kotlin language, that Java doesn't support. Unfortunately, this requires manually setting it for those you want to replace, so it can be slightly boilerplate.

But you can change your import to:

import kotlinx.android...your_view as yourView

This applies to any and all imports, and any types too. It could be done with classes, methods, constants... Whatever you feel like.

Although if you can access the XML files, I recommend you just change the IDs in there. There's no reason not to use camelCase anyways, and it's slightly easier than using as customName in every import.

Related