Asynchronous layout inflation

Lubos Mudrak
Jun 18, 2016 · 2 min read

Enter AsyncLayoutInflater

val inflater = AsyncLayoutInflater(this)
inflater.inflate(resId: Int, parent: ViewGroup) 
inflater.inflate(resId: Int, parent: ViewGroup) 
{ view, resid, parent -> parent.addView(view) }

Drawbacks of using AsyncLayoutInflater

Small sample in Kotlin with use of Kotlin Android Extensions

class MainActivity : AppCompatActivity() {

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

loadFirst.setOnClickListener {
loadAsync(R.layout.async) {
second.text = "I am second TextView"
}
}
}
}

fun MainActivity.loadAsync(@LayoutRes res: Int,
action: View.() -> Unit) =
AsyncLayoutInflater(this).inflate(res, frame)
{ view, resid, parent ->
with(parent) {
addView(view)
action(view)
}
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/frame"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="@dimen/activity_vertical_margin"
android:orientation="vertical"
tools:context="com.cartoon.player.MainActivity">

<TextView
android:id="@+id/loadFirst"
android:layout_width="match_parent"
android:layout_height="48dp"
android:gravity="center"
android:layout_marginBottom="16dp"
android:text="Load f async"/>

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

<TextView
android:id="@+id/first"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="16dp"
android:text="1"/>

<TextView
android:id="@+id/second"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="16dp"
android:text="2"/>

</LinearLayout>

Lubos Mudrak

Written by

I like to code. Opinions expressed here are my own

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade