SNM*_*SNM 7 android kotlin android-recyclerview android-jetpack-compose
因此,我实现了一个惰性列来处理食谱元素列表,问题是它不平滑滚动,如果我快速滚动它会口吃,直到最后一个元素出现并且不平滑滚动。
这是我这边的错误还是我需要添加其他内容?
data class Recipe(
@DrawableRes val imageResource: Int,
val title: String,
val ingredients: List<String>
)
val recipeList = listOf(
Recipe(R.drawable.header,"Cake1", listOf("Cheese","Sugar","water")),
Recipe(R.drawable.header,"Cake2", listOf("Cheese1","Sugar1","Vanilla")),
Recipe(R.drawable.header,"Cake3", listOf("Bread","Sugar2","Apple")))
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
RecipeList(recipeList = recipeList)
}
}
}
@Composable
fun RecipeCard(recipe:Recipe){
val image = imageResource(R.drawable.header)
Surface(shape = RoundedCornerShape(8.dp),elevation = 8.dp,modifier = Modifier.padding(8.dp)) {
Column(modifier = Modifier.padding(16.dp)) {
val imageModifier = Modifier.preferredHeight(150.dp).fillMaxWidth().clip(shape = RoundedCornerShape(8.dp))
Image(asset = image,modifier = imageModifier,contentScale = ContentScale.Crop)
Spacer(modifier = Modifier.preferredHeight(16.dp))
Text(text = recipe.title,style = typography.h6)
for(ingredient in recipe.ingredients){
Text(text = ingredient,style = typography.body2)
}
}
}
}
@Composable
fun RecipeList(recipeList:List<Recipe>){
LazyColumnFor(items = recipeList) { item ->
RecipeCard(recipe = item)
}
}
@Preview
@Composable
fun RecipePreview(){
RecipeCard(recipeList[0])
}
Run Code Online (Sandbox Code Playgroud)
目前(版本1.0.0-alpha02)Jetpack Compose 有 2 个可组合函数用于加载图像资源:
imageResource():这个Composable函数,同步加载图片资源。
loadImageResource():该函数在后台线程中加载图像,一旦加载完成,就会安排重组,并且该函数将返回带有LoadedResource或的延迟图像资源FailedResource
因此,lazyColumn由于您正在同步加载图像,因此您的滚动不顺畅。
因此,您应该使用Chris BanesloadImageResource()命名的库Accompanist,它可以使用 Coil 图像加载库从外部源(例如网络)获取和显示图像。
更新:
使用CoilImage:
首先,添加Accompanist Gradle 依赖项,然后简单地使用CoilImage可组合函数:
CoilImage(data = R.drawable.header)
Run Code Online (Sandbox Code Playgroud)
使用loadImageResource():
val deferredImage = loadImageResource(
id = R.drawable.header,
)
val imageModifier = Modifier.preferredHeight(150.dp).fillMaxWidth()
.clip(shape = RoundedCornerShape(8.dp))
deferredImage.resource.resource?.let {
Image(
asset = it,
modifier = imageModifier
)
}
Run Code Online (Sandbox Code Playgroud)
注意:我在 a 中尝试了两种方法LazyColumnFor,虽然loadImageResource()性能比更好imageResource(),但仍然滚动不顺畅。
所以我强烈推荐使用CoilImage
注 2:要使用 Glide 或 Picasso,请检查Vinay Gaba 的此存储库
| 归档时间: |
|
| 查看次数: |
4883 次 |
| 最近记录: |