Problem with inflating custom ViewGroup.
Unable to start activity Binary XML file line #14: Binary XML file line #14: Error inflating class com.example.interactiveplatform.view.GraphLayout.
I searched about this problem and there is something wrong with constructors.
<LinearLayout
android:id="@+id/graph"
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
tools:context=".MainActivity">
<com.example.interactiveplatform.view.GraphLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
</com.example.interactiveplatform.view.GraphLayout>
</LinearLayout>
class GraphLayout(context: Context, attrs: AttributeSet, var chapterAdapter: ChapterAdapter) : ViewGroup(context, attrs) {
private val detector: GestureDetector
private val mMoveAndScaleHandler: MoveAndScaleHandler
private val myListener: GestureDetector.SimpleOnGestureListener
private var spacing = 0
init {
myListener = object : GestureDetector.SimpleOnGestureListener() {
override fun onDown(e: MotionEvent?): Boolean {
return true
}
}
detector = GestureDetector(context, myListener)
mMoveAndScaleHandler = MoveAndScaleHandler(context, this, chapterAdapter)
}
override fun onLayout(p0: Boolean, p1: Int, p2: Int, p3: Int, p4: Int) {
for(i in 0 until childCount){
val v = getChildAt(i)
v.layout(v.left, v.top, v.right, v.bottom)
}
}
override fun onTouchEvent(event: MotionEvent): Boolean {
detector.onTouchEvent(event)
invalidate()
return mMoveAndScaleHandler.onTouchEvent(event)
}
override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
setMeasuredDimension(400 * chapterAdapter.numberChapters,chapterAdapter.heightScreen)
}
}
When you instantiate your custom view via XML you cannot pass custom constructor parameters like chapterAdapter
. Also, you have to support all Android's view constructors. For example, you can do it like this:
class GraphLayout @JvmOverloads constructor(
context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0
) : ViewGroup(context, attrs, defStyleAttr)