I have created a custom view class extending Android’s WebView, but when I add it to an xml layout, it appears as a gray block. I would like to show a custom layout in place of the gray block to be able to preview it.
The definition of the custom view is as follows:
class CustomView(context: Context, attrs: AttributeSet?) : WebView(context, attrs) {
constructor(context: Context) : this(context, null)
init {
if (isInEditMode) {
//show preview layout
context.getSystemService<LayoutInflater>()!!
.inflate(R.layout.widget_match_preview, this, true)
}
}
}
As can be seen in the code above, I have tried to show a preview in the init block, but it stills shows the gray block in the Android Studio layout preview.
3
Answers
AFAIK this can not be done, as @cactustictacs said, WebView implements its own drawing and can not be changed to another layout. What I ended up doing is overrride the
onDraw(canvas: Canvas)
method, and add the following to render a preview icon at the center of the view:Draw allocation is not a problem since will only be done once while in preview mode in the IDE. The only downside is that the icon is being drawn behind the "CustomView" text but is not big of a deal.
I think you’re missing
addView
:You should:
Result:
In xml: