Challenge: Detail Display - have to set layout_width and layout_height to dp?

My DialogFragment, PhotoCloseupFragment, will always send in 0 for measuredView.width and measuredView.height unless I use dp values for my ImageView layout_width and layout_height.

PhotoCloseupFragment:

class PhotoCloseupFragment : DialogFragment() {

    private val args: PhotoCloseupFragmentArgs by navArgs()

    private var _binding: FragmentPhotoCloseupFragmentBinding? = null
    private val binding
        get() = checkNotNull(_binding) {
            "Cannot access binding because it is null. Is the view visible?"
        }

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        _binding =
            FragmentPhotoCloseupFragmentBinding.inflate(inflater, container, false)
        return binding.root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        binding.closeup.apply {
            doOnLayout { measuredView ->
                val scaledBitmap = getScaledBitmap(
                    args.photoFilePath,
                    measuredView.width, // ALWAYS 0 ------
                    measuredView.height // ALWAYS 0 ------
                )
                setImageBitmap(scaledBitmap)
                tag = args.photoFilePath
            }
        }
    }

XML:

<?xml version="1.0" encoding="utf-8"?>

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_height="match_parent"
    android:layout_width="match_parent">

    <ImageView
        android:id="@+id/closeup"
        android:layout_width="250dp" <!--breaks if match_parent, wrap_content, or 0dp-->
        android:layout_height="250dp" <!--breaks if match_parent, wrap_content, or 0dp-->
        android:scaleType="centerCrop"
        android:adjustViewBounds="true"
        android:importantForAccessibility="no" />

</FrameLayout>

With wrap_content:

I was able to get things working with match_parent as the width and height of my image. There are 2 things that might have gone wrong:

  • When you aren’t overriding onCreateDialog() and showing a custom view instead, you need to set the style for the dialog in onCreate(). Something like:
override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setStyle(STYLE_NO_TITLE, R.style.Theme_CriminalIntent)
}
  • I don’t know exactly what format args.photoFilePath is in, but double check to make sure that you have the full file path for the image when trying to display it. We only save the file path relative to the application’s file directory in our Room database. Look at updatePhoto() in CrimeDetailFragment, specifically when we create photoFile from photoFileName.

I hope this helps out.

2 Likes

Thanks! Setting the style in onCreate fixed it for me.

1 Like