'How to add XML layout to custom view?

I have a custom view like this:

enter image description here

class SquareView : View {

    private lateinit var mRectanglePaint: Paint


    constructor(context: Context?) : super(context) {
        init(null)
    }

    constructor(context: Context?, attrs: AttributeSet?) : super(context, attrs) {
        init(attrs)
    }

    constructor(context: Context?, attrs: AttributeSet?, defStyleAttr: Int) : super(
        context,
        attrs,
        defStyleAttr
    ) {
        init(attrs)
    }

    constructor(
        context: Context?,
        attrs: AttributeSet?,
        defStyleAttr: Int,
        defStyleRes: Int
    ) : super(context, attrs, defStyleAttr, defStyleRes) {
        init(attrs)
    }

    private fun init(attrs: AttributeSet?) {

        mRectanglePaint = Paint().apply {
            isAntiAlias = true
            color = Color.RED
        }

    }


    override fun onDraw(canvas: Canvas) {
        canvas.apply {
            drawRectangle(this)
        }
    }

    private fun drawRectangle(canvas: Canvas) {
        val rect = Rect()
        rect.left = 100
        rect.right = rect.left + 100
        rect.top = 100
        rect.bottom = rect.top + 100

        canvas.drawRect(rect, mRectanglePaint)
    }

}

And, this is my blue_square.xml file:

enter image description here

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:orientation="vertical"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_height="wrap_content">

    <View
        android:id="@+id/blue_square"
        android:layout_width="100dp"
        android:layout_height="100dp"
        android:background="#0000FF" />

</LinearLayout>

I want to add this XML layout to my view and set position to bottom of the red square.

I added this code but this time only the blue square appears.

val inflater = context.getSystemService(Context.LAYOUT_INFLATER_SERVICE) as LayoutInflater
val view = inflater.inflate(R.layout.blue_square, this, true)

I want to include the blue square in my custom view and change its position.

How can I do that? Thank you for your help.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source