我是android的新手,我想为安卓实现Shimmer效果。根据给定的在本文档中
它可以很好地使用 XML 方法,但我也想对组合函数(简而言之,将XML嵌入到可组合函数中)做同样的工作。
以下是XML代码: shimmer_view.xml
<com.facebook.shimmer.ShimmerFrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
tools:context=".presentation.ui.recipe_list.UserListFragment"
android:id="@+id/shimmerFrameLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:shimmer_auto_start="true"
>
<include layout="@layout/shimmer_placeholder_card" />
</com.facebook.shimmer.ShimmerFrameLayout>
我想在其中使用上面的xml文件的片段
class UserListFragment: Fragment() {
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View {
// Traditional Approach Working Fine.
// val view = inflater.inflate(R.layout.shimmer_view, container, false)
// return view
// ComposeView inside fragment
val composeView = ComposeView(requireContext()).apply {
setContent {
Text(text = "Welcome in Compose-World ")
// Here i want To use xml file as a Compose View
}
}
return composeView
}
}
是否有可能将shimmer_view.xml充气或转换为可组合的函数?
或
以某种方式将这个xml嵌入到复合函数中。
供参考,如果有的话,请分享示例代码。会对我们有帮助的。
谢谢
发布于 2021-05-02 15:02:51
我创建了这个函数,它帮助我将XML布局膨胀为一个可组合的实例:
@Composable
fun createAndroidViewForXMLLayout(@LayoutRes resId: Int) {
val context = LocalContext.current
val your_xml_Layout = remember(resId, context) {
LayoutInflater.from(context).inflate(resId,null)
}
AndroidView({ your_xml_Layout })
}
在您的例子中,您只需调用这个函数,如下所示:
class UserListFragment: Fragment() {
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View {
val composeView = ComposeView(requireContext()).apply {
setContent {
Text(text = "Welcome in Compose-World ")
// Here you add the function with the id of your layout **"R.layout.shimmer_view"**
createAndroidViewForXMLLayout(R.layout.shimmer_view)
}
}
return composeView
}
}
发布于 2021-05-03 07:28:01
这里有一个可组合的,它在另一个可组合的内部提供了闪烁的效果:
@Composable
fun Shimmer(modifier: Modifier = Modifier, content: @Composable () -> Unit) {
val context = LocalContext.current
val shimmer = remember {
ShimmerFrameLayout(context).apply {
addView(ComposeView(context).apply {
setContent(content)
})
}
}
AndroidView(
modifier = modifier,
factory = { shimmer }
) { it.startShimmer() }
}
并将其用作:
Shimmer {
// Your placeholder
Box(modifier = Modifier.size(100.dp).background(Color.LightGray))
}
https://stackoverflow.com/questions/67354302
复制相似问题