in CameraXBasic/app/src/main/java/com/android/example/cameraxbasic/fragments/GalleryFragment.kt [89:173]
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
//Checking media files list
if (mediaList.isEmpty()) {
fragmentGalleryBinding.deleteButton.isEnabled = false
fragmentGalleryBinding.shareButton.isEnabled = false
}
// Populate the ViewPager and implement a cache of two media items
fragmentGalleryBinding.photoViewPager.apply {
offscreenPageLimit = 2
adapter = MediaPagerAdapter(childFragmentManager)
}
// Make sure that the cutout "safe area" avoids the screen notch if any
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
// Use extension method to pad "inside" view containing UI using display cutout's bounds
fragmentGalleryBinding.cutoutSafeArea.padWithDisplayCutout()
}
// Handle back button press
fragmentGalleryBinding.backButton.setOnClickListener {
Navigation.findNavController(requireActivity(), R.id.fragment_container).navigateUp()
}
// Handle share button press
fragmentGalleryBinding.shareButton.setOnClickListener {
mediaList.getOrNull(fragmentGalleryBinding.photoViewPager.currentItem)?.let { mediaFile ->
// Create a sharing intent
val intent = Intent().apply {
// Infer media type from file extension
val mediaType = MimeTypeMap.getSingleton()
.getMimeTypeFromExtension(mediaFile.extension)
// Get URI from our FileProvider implementation
val uri = FileProvider.getUriForFile(
view.context, BuildConfig.APPLICATION_ID + ".provider", mediaFile)
// Set the appropriate intent extra, type, action and flags
putExtra(Intent.EXTRA_STREAM, uri)
type = mediaType
action = Intent.ACTION_SEND
flags = Intent.FLAG_GRANT_READ_URI_PERMISSION
}
// Launch the intent letting the user choose which app to share with
startActivity(Intent.createChooser(intent, getString(R.string.share_hint)))
}
}
// Handle delete button press
fragmentGalleryBinding.deleteButton.setOnClickListener {
mediaList.getOrNull(fragmentGalleryBinding.photoViewPager.currentItem)?.let { mediaFile ->
AlertDialog.Builder(view.context, android.R.style.Theme_Material_Dialog)
.setTitle(getString(R.string.delete_title))
.setMessage(getString(R.string.delete_dialog))
.setIcon(android.R.drawable.ic_dialog_alert)
.setPositiveButton(android.R.string.yes) { _, _ ->
// Delete current photo
mediaFile.delete()
// Send relevant broadcast to notify other apps of deletion
MediaScannerConnection.scanFile(
view.context, arrayOf(mediaFile.absolutePath), null, null)
// Notify our view pager
mediaList.removeAt(fragmentGalleryBinding.photoViewPager.currentItem)
fragmentGalleryBinding.photoViewPager.adapter?.notifyDataSetChanged()
// If all photos have been deleted, return to camera
if (mediaList.isEmpty()) {
Navigation.findNavController(requireActivity(), R.id.fragment_container).navigateUp()
}
}
.setNegativeButton(android.R.string.no, null)
.create().showImmersive()
}
}
}