2

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?

Ryan M
  • 18,333
  • 31
  • 67
  • 74
R Rifa Fauzi Komara
  • 1,915
  • 6
  • 27
  • 54

1 Answers1

1

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.

Ryan M
  • 18,333
  • 31
  • 67
  • 74
  • Hi bro, How can I do if want to add more than 1 an `` tag? – R Rifa Fauzi Komara Mar 12 '20 at 08:00
  • Could you clarify a bit what you mean by "add more than 1"? If you want to include multiple layouts, you could certainly do that by calling `inflate` more than once, but since it's a FrameLayout, they'd just end up on top of each other. You'd probably want to wrap them in a LinearLayout or something. – Ryan M Mar 12 '20 at 08:14
  • Each include tag is equivalent to an `inflate`, so you could just call `inflate` multiple times, as I mentioned in my previous comment. – Ryan M Mar 12 '20 at 08:40
  • So, in my new XML I just add `ShimmerFrameLayout` and inside it add `LinearLayout`. Then for the `include tag` add from Kotlin code? It's automatic the tag I add from Kotlin code will inside `LinearLayout`? – R Rifa Fauzi Komara Mar 12 '20 at 08:54