Home > Software engineering >  How to show a preview for a custom view in Android Studio
How to show a preview for a custom view in Android Studio

Time:12-22

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.

CodePudding user response:

I think you're missing addView:

class CustomView(context: Context, attrs: AttributeSet?) : WebView(context, attrs) {

    constructor(context: Context) : this(context, null)

    init {
        if (isInEditMode) {
            // inflate the preview layout
            val previewLayout = context.getSystemService<LayoutInflater>()!!
                .inflate(R.layout.widget_match_preview, null)

            // add the preview layout as a child view of the CustomView
            addView(previewLayout)
        }
    }
}

CodePudding user response:

You should:

class CustomView : LinearLayout {

    constructor(context: Context) : super(context)
    constructor(context: Context, attrs: AttributeSet) : super(context, attrs)
    constructor(context: Context, attrs: AttributeSet, defStyleAttr: Int) : super(context, attrs, defStyleAttr)

    init {
        LayoutInflater.from(context).inflate(R.layout.widget_match_preview, this, true)
        if (!isInEditMode) {
            // skip code
        }
    }
}
  • Result: previewlayout

  • In xml:

      <?xml version="1.0" encoding="utf-8"?>
      <LinearLayout 
       xmlns:android="http://schemas.android.com/apk/res/android"
          android:layout_width="match_parent"
          android:layout_height="match_parent"
          android:background="@color/red"/>
    
  • Related