这是一个可组合的函数。当我点击CardView时,文章应该在Android视图中打开。我不确定如何实现这一点。
我也尝试过使用lambda,但没有成功。
我希望在单击NewsCardView(Card View)函数时调用可组合函数ShowOnWebView,但编译器显示错误:
"@Composable invocations can only happen from the context of a @Composable function"
当单击CardView时如何调用我的函数?
我也尝试过使用lambda,但没有成功。
我希望在单击NewsCardView(Card View)函数时调用可组合函数ShowOnWebView,但编译器显示错误:
"@Composable invocations can only happen from the context of a @Composable function"
当单击CardView时如何调用我的函数?
@Composable
fun NewsCardView(
article: Article,
modifier: Modifier = Modifier,
) {
Card(
modifier = modifier
.height(150.dp)
.fillMaxWidth()
.padding(2.dp)
.clickable {
// I want to call ShowOnWebView here
},
elevation = 5.dp,
backgroundColor = Color.White
) {
val painter = rememberImagePainter(data = article.urlToImage) {
crossfade(1000)
error(R.drawable.ic_placeholder)
placeholder(R.drawable.ic_placeholder)
}
Row(
modifier = Modifier
.fillMaxSize(),
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.SpaceEvenly
) {
Column(
modifier = Modifier.fillMaxWidth(.3f),
verticalArrangement = Arrangement.Center,
horizontalAlignment = Alignment.CenterHorizontally
) {
Image(
modifier = Modifier.size(100.dp),
painter = painter,
contentDescription = "News",
contentScale = ContentScale.Crop,
)
Text(
text = article.author ?: "",
fontSize = 12.sp,
)
Text(
text = article.publishedAt,
fontSize = 12.sp,
)
}
Column(
modifier = Modifier.fillMaxWidth(.7f),
verticalArrangement = Arrangement.Center,
horizontalAlignment = Alignment.CenterHorizontally
) {
Text(modifier = Modifier.fillMaxWidth(),
text = article.title,
color = Color.Black,
fontWeight = FontWeight.Bold,
fontSize = 16.sp
)
Text(modifier = Modifier.fillMaxWidth(),
text = article.description ?: "",
color = Color.Black,
fontWeight = FontWeight.Medium,
fontSize = 14.sp
)
}
}
}
}
这个可组合函数在AndroidView中显示一篇文章:
@Composable
fun ShowOnWebView(url:String) {
val context= LocalContext.current
AndroidView(factory = {
WebView(context).apply {
webViewClient= WebViewClient()
loadUrl(url)
}
})
}