首页 > 解决方案 > 如何在 Kotlin 中以编程方式设置 ShimmerLayout 的布局?

问题描述

注意:我的问题与不同。

我想ShimmerLayout在 Kotlin 代码中以编程方式设置布局。那有可能吗?

目前,我可以像这样通过 XML 设置布局:

<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>

@layout/shimmer_banner我们可以从 Kotlin 代码中设置布局 ( ) 吗?

所以,xml是这样的:

<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}"/>

在 Kotlin 代码中,像这样调用这个 xml: shimmerLayout.set = R.layout.shimmer_banner,但它没有以编程方式从 Kotlin 代码设置布局的功能。

如何通过 Kotlin 代码仍然有一个LinearLayoutwith vertical+ 可以做到这一点add more 1 <include> tag

标签: androidkotlinandroid-layoutshimmer

解决方案


通过<include>标签包含的布局只是膨胀到父级中,因此您可以简单地使用 LayoutInflater 来做到这一点。

假设(根据您的问题)您对微光布局的引用为shimmerLayout,您可以这样做:

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

如果您已经有视图,要更改它,您需要执行shimmerLayout.removeAllViews(),然后执行上述操作。


推荐阅读