R Rifa Fauzi Komara
R Rifa Fauzi Komara

Reputation: 2128

How do I set the layout for ShimmerLayout programmatically in Kotlin?

NOTE: My question is different from this.

I want to set the layout of ShimmerLayout programmatically in Kotlin code. Is that possible to do?

Currently, I can set the layout via XML like this:

<com.facebook.shimmer.ShimmerFrameLayout
    android:id="@+id/shimmerLayout"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:visibility="@{showSimmerBanner ? View.VISIBLE : View.GONE, default=gone}">

         <LinearLayout
            android:id="@+id/shimmerOrientation"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical">

            <include layout="@layout/shimmer_banner" />
            <include layout="@layout/shimmer_banner" />
            <include layout="@layout/shimmer_banner" />

        </LinearLayout>

 </com.facebook.shimmer.ShimmerFrameLayout>

Can we set the layout (@layout/shimmer_banner) from the Kotlin code?

So, the xml is like this:

<com.facebook.shimmer.ShimmerFrameLayout
   android:id="@+id/shimmerLayout"
   android:layout_width="match_parent"
   android:layout_height="wrap_content"
   android:visibility="@{showSimmerBanner ? View.VISIBLE : View.GONE, default=gone}"/>

And in Kotlin code call this xml like this: shimmerLayout.set = R.layout.shimmer_banner, but it doesn't have a function to set layout from Kotlin code programmatically.

How to do that via Kotlin code with still have a LinearLayout with vertical + can add more 1 <include> tag?

Upvotes: 2

Views: 1014

Answers (1)

Ryan M
Ryan M

Reputation: 20167

A layout included via an <include> tag is just inflated into the parent, so you can simply use a LayoutInflater to do it.

Assuming (from your question) that you have a reference to the shimmer layout as shimmerLayout, you can just do:

val inflater = LayoutInflater.from(shimmerLayout.context)
inflater.inflate(R.layout.shimmer_banner, shimmerLayout)

To change it if you already have views in it, you'd need to do shimmerLayout.removeAllViews(), then do the above.

Upvotes: 1

Related Questions