在Kotlin文件中找不到Drawable

3
我想从非Activity类中访问可绘制资源,这是因为我希望将我的组合函数放在另一个文件中,而不是在主文件中。问题是,从主文件可以访问R.drawable.header,但从其他创建的文件中却不能。
请看下图:enter image description here
import androidx.annotation.DrawableRes
import androidx.compose.foundation.Image
import androidx.compose.foundation.Text
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.lazy.LazyColumnFor
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.Surface
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.res.imageResource
import androidx.compose.ui.unit.dp
import androidx.ui.tooling.preview.Preview
import com.example.jetexample.ui.typography

@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)
            }
        }
    }
}

我知道这与上下文有关,这就是为什么我无法访问我认为的资源,但我已经尝试了ContextAmbient,仍然无法访问。

1个回答

6

检查一下R.drawable是否指向您项目中的drawable资源文件夹。我看您没有在文件中导入任何资源。

import com.example.jetexample.R

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接