The conflict of the synthetic properties of Kotlin

I am new to Kotlin. Among other very interesting things, I found Android extensions that , according to the documentation , should allow me to use activities without having to findViewById .

This actually works very well, adding only this line to my import:

 import kotlinx.android.synthetic.main.<layout>.* 

The problem is that two different layouts contain a widget with the same identifier (i.e. the same name for the synthetic property),
for example two different TextView with id txtTitle . Let's say the first one relates to activity, and the second one refers to the layout used inside the adapter.

When I try to call a method in the first TextView (one of the actions), I do not see the expected result, as if the call was made on a different view. As a confirmation of this, when I call txtTitle.parent , I see the parent and siblings of another txtTitle , not the expected ones.

Am I doing something wrong? The only ways I found to get around this problem is to use different names in all my layouts or to continue to use findViewById , but it would be very unfortunate to waste this language function ...

+5
source share
3 answers

kotlin import documentation says

If there is a clash of names, we can eliminate the ambiguity using the as keyword to locally rename the related object

So, you can try to import layouts with different aliases:

 import kotlinx.android.synthetic.main.<layoutActivity>.* as lActivity import kotlinx.android.synthetic.main.<layoutView>.* as lView 

And use text images with the appropriate qualifier: lActivity.txtTitle and lView.txtTitle

+3
source

Another possible solution to your problem is to simply import and omit the other, assuming that all the identifiers you need are present in this.

At the end of the day, similar identifiers point to the same thing, and it really does not matter if it was imported from one layout or another.

Hope that helps

0
source

You can try below so that the TextView same id from a different layout.

 import kotlinx.android.synthetic.main.activity_main.text_hello as lActivity import kotlinx.android.synthetic.main.extra_layout.text_hello as lView 

use lActivity.text = "Some text" for the TextView from activity_main and lView.text = "Some text" for the TextView from extra_layout .

-1
source

Source: https://habr.com/ru/post/1263212/


All Articles