I imported local modules to my Android Studio project using gradle. Whenever I create a custom View class that imports any of those modules' class, Android Studio fails to render it in the layout preview (even if it still works well when I run the app).
I couldn't find any topic talking about this specific issue. I tried to clean, clear the cache and rebuild but I couldn't get it to work. Also changing my module import path from absolute to relative didn't solve the issue.
Here is how I imported my modules :
settings.gradle:
include ':app'
include(':mylocalmodule')
project(':mylocalmodule').projectDir = new File("C:\\Home\\MyLocalModule\\mylocalmodule")
app's build.gradle:
...
dependencies {
...
implementation project(":mylocalmodule")
...
}
...
I created a test view:
package com.ltei.myapp.view
import android.content.Context
import android.util.AttributeSet
import android.view.View
import com.ltei.mylocalmodule.RGB
class TestView : View {
private val rgb = RGB(255, 0, 0)
constructor(context: Context) : super(context)
constructor(context: Context, attrs: AttributeSet) : super(context, attrs)
constructor(context: Context, attrs: AttributeSet, defStyleAttr: Int) : super(context, attrs, defStyleAttr)
override fun onDraw(canvas: Canvas?) {
super.onDraw(canvas)
if (canvas == null) return
canvas.drawColor(rgb.getColor())
}
}
And added it to an xml layout
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<com.ltei.myapp.view.TestView
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</LinearLayout>
I expect the preview renderer to render my view without any error but I get the following output :
The following classes could not be instantiated:
- com.ltei.myapp.view.TestView (Open Class, Show Exception, Clear Cache)
Tip: Use View.isInEditMode() in your custom views to skip code or show sample data when shown in the IDE.
If this is an unexpected error you can also try to build the project, then manually refresh the layout.
Exception Details java.lang.NoClassDefFoundError: com/ltei/mylocalmodule/RGB
at com.ltei.myapp.view.TestView.<init>(TestView.kt:14)
at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:730)
at android.view.LayoutInflater.rInflate_Original(LayoutInflater.java:863)
at android.view.LayoutInflater_Delegate.rInflate(LayoutInflater_Delegate.java:72)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:837)
at android.view.LayoutInflater.rInflateChildren(LayoutInflater.java:824)
at android.view.LayoutInflater.inflate(LayoutInflater.java:515)
at android.view.LayoutInflater.inflate(LayoutInflater.java:394)