Search code examples
androidkotlinlayout-inflaterandroid-inflatekotlin-extension

Kotlin : The specified child already has a parent. You must call removeView() on the child's parent first


Can anyone tell me what is the problem. This is the code:

package com.mohdjey.user.inflate

import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.os.strictmode.WebViewMethodCalledOnWrongThreadViolation
import android.view.LayoutInflater
import android.view.View
import android.widget.ImageView
import android.widget.LinearLayout
import android.widget.TextView
import com.mohdjey.user.inflate.R.id.root_layout
import com.mohdjey.user.inflate.R.layout.activity_main
import kotlinx.android.synthetic.main.activity_main.*
import kotlinx.android.synthetic.main.activity_main.view.*

 class MainActivity : AppCompatActivity() {

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(activity_main)

    var inflater: LayoutInflater? = null
    var view: View? = null


 //   inflater.inflate(R.layout.child_layout_to_merge, parent_layout, true);
    view = inflater?.inflate(R.layout.another_view , null)

    val layout = findViewById<LinearLayout>(R.id.root_layout)

    layout.addView(layout)


} }

I am practicing layout inflate.

I don't Know what to write.


Solution

  • You're trying to add the LinearLayout with the ID root_layout as its own child here:

    layout.addView(layout)
    

    Perhaps you meant to add your newly inflated View as its child?

    layout.addView(view)