I don't understand the main difference between true or false for the third parameters of inflate method, any helpful examples.
-
https://stackoverflow.com/a/5027921/10182897 read answer – Ashish Oct 17 '20 at 11:06
-
https://www.myandroidsolutions.com/2012/06/19/android-layoutinflater-turorial/ you can read more – Ashish Oct 17 '20 at 11:07
1 Answers
Let's suppose we have this very simple layout:
view_red_square.xml
<?xml version="1.0" encoding="utf-8"?>
<View xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="200dp"
android:layout_height="200dp"
android:background="#FA8072" />
And this layout used by our main activity:
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent"
>
</FrameLayout>
Now let's try to inflate the view_red_square.xml
layout in MainActivity
and understand what happens.
MainActivity.kt
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val container = findViewById<FrameLayout>(R.id.container)
val inflatedView = layoutInflater.inflate(R.layout.view_red_square, container, false)
Toast.makeText(this, "Is the view inflated: $inflatedView", Toast.LENGTH_SHORT).show()
}
}
The third boolean parameter for LayoutInflater.inflate
, as the documentation points, stands for:
attachToRoot: Whether the inflated hierarchy should be attached to the root parameter? If false, root is only used to create the correct subclass of LayoutParams for the root view in the XML.
So, going back to our main activity. The false
boolean value indicates that the view inflated shouldn't be added to the root
, also specified in the inflate method.
Using the above code for MainActivity
. We can verify, with the layout inspector, that the view is not added to the container when inflating the view with attachToRoot
set to false
.
A solution for adding the view to our container would be to manually add the view to our view group, by using container.addView(inflatedView)
.
Now let's see what happens when we switch that attachToRoot
boolean to true
. Let's again use the layout inspector.
val inflatedView = layoutInflater.inflate(R.layout.view_red_square, container, true)
As you can see, the view is now added to the root
which is our container. Therefore, we can conclude that attachToRoot
, adds the inflated view to the given root if its value is true
.

- 2,398
- 15
- 21