可以用Compose 加入一些最為實用的程式庫。
rememberLauncherForActivityResult() API 可助您從可組合項中取得 Activity 結果
@Composable
fun Greeting(name: String) {
var imageUri by remember { mutableStateOf<Uri?>(null) }
val launcher = rememberLauncherForActivityResult(GetContent()) { uri: Uri? ->
imageUri = uri
}
Column {
Button(onClick = { launcher.launch("image/*") }) {
Text(text = "Load Image")
}
Image(
painter = rememberImagePainter(imageUri),
contentDescription = "My Image"
)
}
}
顯示結果:
可組合項可以使用 BackHandler 以攔截 Back key 事件
@Composable
fun Greeting(name: String) {
...
var backHandlingEnabled by remember { mutableStateOf(true) }
BackHandler(backHandlingEnabled) {
// Handle back press
Log.d("kevin","press back key")
}
...
}
顯示結果:
Instacart 的 Coil 程式庫提供透過外部來源載入圖片的可組合函式,例如透過網路載入遠端圖片。
權限
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
build.gradle
implementation("io.coil-kt:coil-compose:2.2.1")
@Composable
fun Greeting(name: String) {
...
val painter = rememberAsyncImagePainter(
ImageRequest.Builder(LocalContext.current).data(data = "https://picsum.photos/300/300")
.apply(block = fun ImageRequest.Builder.() {
crossfade(true)
}).build()
)
Box {
Image(
painter = painter,
contentDescription = stringResource(R.string.image_content_desc),
modifier = Modifier.align(Alignment.Center)
)
when (painter.state) {
is AsyncImagePainter.State.Loading -> {
// Display a circular progress indicator whilst loading
Log.d("kevin","load image ...")
}
is AsyncImagePainter.State.Error -> {
// If you wish to display some content if the request fails
}
}
} ...
}
顯示結果:
https://developer.android.com/jetpack/compose/libraries
Kotlin 的技術傳教士 - 范聖佑 近期也出了一本關於 Collection 的書 - Kotlin Collection 全方位解析攻略
裡面也有蠻多 operator 的介紹,歡迎大家有興趣的參考看看
https://www.tenlong.com.tw/products/9786263331136