Search code examples
androidandroid-custom-view

Creating CustomView by inheriting another CustomView


I'm working on a project where I have to use different types of custom views. These custom views share some common functionalities, so I decided to create a superclass and put all the common functionalities there. Let's call my superclass BaseCustomView and the subclass ACustomView.

Here is what my BaseCustomView looks like:

open class BaseCustomView@JvmOverloads constructor(context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0) :
    FrameLayout(context, attrs, defStyleAttr) {

    protected fun saveDetails() {
        // Saving details
   }
}

I call this function from my subclass. Here is what my ACustomView looks like this:

class ACustomView@JvmOverloads constructor(context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0
) : BaseCustomView(context, attrs, defStyleAttr) {
    
    fun startProcess() {
        saveDetails()
        //Start the process
    }

}

This looks fine till here. Now when I use ACustomView in my fragment and call the startProcess() function using viewBinding, it gives me the following error: Unresolved reference: startProcess

Here is the code I used in the fragment to call the function:

binding.customView.startProcess()

Can anyone please help me with this issue? I have no idea what I am doing wrong. Any help is appreciated. Thanks!


Solution

  • Finally, I could make it work. As explained by @ShlomiKatriel, I was facing this issue because the generated binding class created a View class instead of ACustomView.

    I was able to solve this issue by first using the findViewById(), running the app and then replacing findViewById() with the generated binding class. For some reason, after using the findViewById(), it generates the correct binding class. 🤦‍♂️