Kotlin synthetic extension to view

I have a layout with some views, one of them has an id title_whalemare

 import kotlinx.android.synthetic.main.controller_settings.* import kotlinx.android.synthetic.main.view_double_text.* class MainSettingsController : BaseMvpController<MvpView, MvpPresenter>() { val title: TextView = title_whalemare override fun getLayout(): Int { return R.layout.controller_settings } } 

I am trying to find it using kotlin extensions , but I can not, because I get the following error

None of the following candidates are applicable due to receiver type mismatch None of the following candidates are applicable due to receiver type mismatch

controller_settings.xml

 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical"> <TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:id="@+id/title_whalemare"/> </LinearLayout> 

Where is my mistake?

+5
source share
1 answer

What the error is trying to tell you is that you can only access views with extensions either inside an Activity or a Fragment . This is because it is exactly the same to find views with the specified identifiers, like what you do manually, just calls Activity.findViewById() and Fragment.getView().findViewById() , and then the type that applies to a particular subclass of View . I assume your controller is not an Activity or Fragment .

There is another way to use extensions if you can somehow pass the root view of your layout to the controller. Then you can do the following:

 val title: TextView = rootView.title_whalemare 

Again, this is just a replacement for calling View.findViewById() and cast.

+6
source

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


All Articles