4

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>
Sergey Shustikov
  • 15,377
  • 12
  • 67
  • 119

2 Answers2

2

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

EpicPandaForce
  • 79,669
  • 27
  • 256
  • 428
1

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.

Zoe
  • 27,060
  • 21
  • 118
  • 148
  • Thing is, sometimes I'd like to use an id that is something like "local" to current activity. If I use this local id in XML, it can clash with other IDs in other layouts. In this case it would be great to have such option. – Vadim Kotov Jul 25 '19 at 14:20