Unresolved reference for synthetic view when layout is in library module

前端 未结 10 2124
醉梦人生
醉梦人生 2020-12-12 21:37

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 refer

10条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-12 21:57

    My scenario was : I needed base class (from lib) view references in child classes (app module) and had minimum number of view references from Library Module's base classes.

    I would say, it's kind a fix and not a solution.

    Solution #1 Get a view reference from Base class

    //lib module snippet
    import kotlinx.android.synthetic.main.view_user_input.*
    
    class LibModuleBaseActivity : AppCompatActivity() {
    
       override fun onCreate(savedInstanceState: Bundle?) {
            super.onCreate(savedInstanceState)
            setContentView(R.layout.view_user_input)
       }
    
        protected val vFirstName: TextView by lazy { tvFirstName }
        ...........
    }
    
    
    //app module snippet
    class AppModuleActivity : LibModuleBaseActivity() {
    
        fun setUserDetails(name: String) {
            vFirstName.text = name
        }
    }
    

    Solution #2 Get the task done by Base Class

    //lib module snippet
    import kotlinx.android.synthetic.main.view_user_input.*
    
    class LibModuleBaseActivity : AppCompatActivity() {
        protected fun setUserDetails(name: String) {
            tvFirstName.text = name
        }
        ...........
    }
    
    
    //app module snippet
    class AppModuleActivity : LibModuleBaseActivity() {
        ............
        setUserDetails("user_name")
    }
    

    Note: This works only if you are inheriting from lib module and where your Base class is inflating views.

提交回复
热议问题