Search code examples
androidimageviewcardview

Set height and width of a cardView in android


Im trying to set a width and height for my cardView, so once I download an image from the database, a cardView is added by it stretches the image and can't control the height, im trying to do it programatically. This is what i've got.

public void CreateCardView(final Users u) throws IOException

    {
        CardView.LayoutParams params = new CardView.LayoutParams(
                CardView.LayoutParams.WRAP_CONTENT,
                CardView.LayoutParams.WRAP_CONTENT
        );
        params.setMargins(10,10,10,20);
        params.width = 500;

        mLoginFormView = findViewById(R.id.containerGrid);
        CardView card = new CardView(this);
        card.setLayoutParams(params);
        card.setRadius(9);

        card.setCardElevation(9);
        LinearLayout.LayoutParams par = new LinearLayout.LayoutParams(
                LinearLayout.LayoutParams.MATCH_PARENT,
                LinearLayout.LayoutParams.MATCH_PARENT
        );
        LinearLayout lin = new LinearLayout(this);
        lin.setOrientation(LinearLayout.VERTICAL);
        lin.setLayoutParams(par);

        final  ImageButton Name = new ImageButton(this);

        Name.setAdjustViewBounds(true);
        Name.setScaleType( ImageView.ScaleType.CENTER);
        mLoginFormView.bringToFront();
        //  Name.setBackground(bdrawable);
        Name.setAdjustViewBounds(true);


        //Name.setImageBitmap(i.getImage().get(0));
        lin.bringToFront();
        mLoginFormView.addView(card);

        card.setElevation(15);
        System.out.println("Hello?");

        //Name.setImageBitmap( scaled);
        TextView username = new TextView(this);
        TextView sport = new TextView(this);
        username.setText(u.getUsername());
        sport.setText(u.getEmail());

        lin.addView(Name);
        lin.addView(username);
        lin.addView(sport);


        card.addView(lin);
        card.setElevation(15);

Solution

  • Instead of this code:

    CardView.LayoutParams params = new CardView.LayoutParams(
                    CardView.LayoutParams.WRAP_CONTENT,
                    CardView.LayoutParams.WRAP_CONTENT
            );
            params.setMargins(10,10,10,20);
            params.width = 500;
    

    Try this code:

    card.setLayoutParams(new LayoutParams(width, height));