Search code examples
kotlincardview

ImageView is not respecting the size of the CardView


I am trying to make some sort of gallery app. I would like to display images inside of a ScrollView inside a GridLayout so I used CardView for this and it looks like this:

CardView without images

But when I put ImageView inside each CardView, the CardView spreads and fills the whole ScrollView. Here's a preview:

CardView with ImageView inside

The CardView is created programatically. Here's the code

    fun CreateCardView(ItemCount: Int){
    for (i in 1 until ItemCount){

        /////////////////////CARD VIEW//////////////////////////////
        val card_view = CardView(this)
        card_view.radius = 8F
        card_view.setContentPadding(8,8,8,8)
        card_view.setCardBackgroundColor(Color.LTGRAY)
        card_view.cardElevation = 8F
        val param = GridLayout.LayoutParams()
        param.rowSpec = GridLayout.spec(GridLayout.UNDEFINED, 1f)
        param.columnSpec = GridLayout.spec(GridLayout.UNDEFINED, 1f)
        card_view.layoutParams = param
        val param2 = card_view.layoutParams as GridLayout.LayoutParams
        param2.setMargins(10,10,10,10)
        card_view.layoutParams = param2
        subLayoutGrid?.addView(card_view)
        ////////////////////////END//////////////////////////////////////

        ///////////////////////IMAGEVIEW////////////////////////////////
        val img = ImageView(this)
        val imageparams = WindowManager.LayoutParams(
            WindowManager.LayoutParams.WRAP_CONTENT,
            WindowManager.LayoutParams.WRAP_CONTENT
        )
        img.layoutParams = imageparams
        img.scaleType = ImageView.ScaleType.CENTER_CROP
        img.setImageResource(R.drawable.animaleight)
        card_view.addView(img)
        ////////////////////////END///////////////////////////



    }

}

How can I put ImageView inside the CardView without filling the whole ScrollView?


Solution

  • I've already fixed my problem. I've tried to use a 40px x 40px Picture then it worked the way I want to. See the image: Screenshot 1

    It seems like when you use high resolution Picture, the app cant handle the populating of ImageView in GridLayout.