问题描述
我正在尝试从非Activity类访问可绘制资源,这是因为我想将可组合函数放在另一个文件中,而不是将其放在主文件中,所以我可以从Main文件中访问R.drawable.header
,但无法访问其他创建的文件
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仍然无法做到
解决方法
检查R.drawable
是否指向您项目中的可绘制资源文件夹。如我所见,您尚未在文件中导入资源。
import com.example.jetexample.R