How to set a correct aspect ratio using CameraX?

did you try it?

    val metrics = DisplayMetrics().also { viewFinder.display.getRealMetrics(it) }
    val screenSize = Size(metrics.widthPixels, metrics.heightPixels)
    val screenAspectRatio = Rational(metrics.widthPixels, metrics.heightPixels)

    val viewFinderConfig = PreviewConfig.Builder().apply {
            //...
            setTargetResolution(screenSize)
            setTargetAspectRatio(screenAspectRatio)
            setTargetRotation(viewFinder.display.rotation)
        }.build()

    val preview = AutoFitPreviewBuilder.build(viewFinderConfig, viewFinder)

And AutoFitPreviewBuilder you can find here: https://gist.github.com/yevhenRoman/90681822adef43350844464be95d23f1

I would recommend you to set width and height for your TextureView using dp or constaraints. Let me know if it works for you, thanks!