0

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.

Vadim Kotov
  • 8,084
  • 8
  • 48
  • 62
Jeylani Osman
  • 199
  • 3
  • 13

2 Answers2

2

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)
zsmb13
  • 85,752
  • 11
  • 221
  • 226
  • It shows another error "Cannot add a null child view to a ViewGroup" – Jeylani Osman Jul 02 '18 at 15:44
  • If this above is all your code, that's because you didn't initialize `inflater` yet. You can do so with `inflater = LayoutInflater.from(this)`, for example, since you're in an `Activity`. – zsmb13 Jul 02 '18 at 15:49
  • Even better, you can just use the property `layoutInflater` (from the Activity's java getLayoutInflater). That will be non-null. – Brian Yencho Jul 03 '18 at 15:58
0

Your entire code block should just be

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(activity_main)
    val root = findViewById<LinearLayout>(R.id.root_layout)
    val view = layoutInflater.inflate(R.layout.another_view, root, false)
    root.addView(view)
}

That being said, it's not clear why you don't just include your R.layout.another_view directly in your main layout.

Brian Yencho
  • 2,748
  • 1
  • 18
  • 19