Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unresolved reference for synthetic view when layout is in library module

using Kotlin 1.20.20 (not that it matters, older versions behaves the same)

When layout is in separate library module Android Studio has no problem finding and referencing the view

import kotlinx.android.synthetic.main.view_user_input.*

But when I try to compile app it fails with Unresolved reference: view_user_input on :app:compileDebugKotlin.

Everything works fine when view is referenced IN the library module.

Am I missing something here?

Adding project structure. All modules are using kotlin and kotlin-extensions.

build.gradle
app/
  build.gradle //main application
library-module-a/
  build.gradle //library application
library-module-b/
  build.gradle //library application

Here is an example app https://github.com/mjurkus/KotlinxTest

Registered issue for that in KT tracker

like image 467
Martynas Jurkus Avatar asked Jan 22 '18 09:01

Martynas Jurkus


3 Answers

Update:

Synthetic view references have been deprecated and will not be supported in the future.

The current recommended solution is to use ViewBinding (or wait for Jetpack Compose)

Original Answer:

One way to solve this is to create an "alias" property that can be consumed from other modules:

// SyntheticExports.kt
package com.example.synthetic.exported

import kotlinx.android.synthetic.main.layout_in_library.*

inline val Activity.exported_text_view get() = text_view

Then on the other module:

// MainActivity.kt
import com.example.synthetic.exported.exported_text_view

exported_text_view.text = "example"

That works for us. Have to create different extensions for view, fragment, etc. It's a bit tedious to have to do them manually but this is the simplest workaround we found.

Extra: This is also a decent method to export synthetic extensions as part of a public library too, not just in an internal module.

like image 126
pablisco Avatar answered Nov 09 '22 02:11

pablisco


None of the above answers actually helped me . Add both these plugins in your app level build.gradle file on top :

apply plugin: 'kotlin-android-extensions'
apply plugin: 'kotlin-android'

This should solve the issue .

OR

plugins {
    id 'kotlin-android-extensions'
    id 'kotlin-android'
}
like image 10
Medha Avatar answered Nov 09 '22 02:11

Medha


I also got this issue and my solution is:

  • Don't use import kotlinx.android.synthetic.main....*

  • Use findViewById()

For example I changed from

textview_id.text = "abc"

to

findViewById(R.id.textview_id).text = "abc"
like image 4
Anh Duy Avatar answered Nov 09 '22 03:11

Anh Duy