i know this is a trivial question well answered using java, but i'm sure there are new APIs
to make things easier such as
val getContent = registerForActivityResult(GetContent()) { uri: Uri? -> // Handle the returned Uri }
and
val takePicture = registerForActivityResult(ActivityResultContracts.TakePicture()) { success: Boolean ->
if (success) {
// The image was saved into the given Uri -> do something with it
}
}
val imageUri: Uri = ...
button.setOnClickListener {
takePicture.launch(imageUri)
}
Q: How to implement the above question using kotlin and implementing the lastest APIs
for that
PS: this is question is still valid if answers provided become depreciated or obsolete.
Here is my code, hope this help
fun takePicture() {
val root =
File(Environment.getExternalStorageDirectory(), BuildConfig.APPLICATION_ID + File.separator)
root.mkdirs()
val fname = "img_" + System.currentTimeMillis() + ".jpg"
val sdImageMainDirectory = File(root, fname)
viewModel.profileImageUri = FileProvider.getUriForFile(requireContext(), context?.applicationContext?.packageName + ".provider", sdImageMainDirectory)
takePicture.launch(viewModel.profileImageUri)
}
val takePicture = registerForActivityResult(ActivityResultContracts.TakePicture()) { success: Boolean ->
if (success) {
// The image was saved into the given Uri -> do something with it
Picasso.get().load(viewModel.profileImageUri).resize(800,800).into(registerImgAvatar)
}
}
private val pickImages = registerForActivityResult(ActivityResultContracts.GetContent()){ uri: Uri? ->
uri?.let { it ->
// The image was saved into the given Uri -> do something with it
Picasso.get().load(it).resize(800,800).into(registerImgAvatar)
}
}
Then call the function when press button:
btnSelectFromGallery.setOnClickListener {
pickImages.launch("image/*")
}
btnTakePicture.setOnClickListener {
takePicture()
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.