在 android 中设置 cardView 的高度和宽度

Set height and width of a cardView in android

我正在尝试为我的 cardView 设置宽度和高度,所以一旦我从数据库下载图像,就会添加一个 cardView 来拉伸图像并且无法控制高度,我正在尝试以编程方式进行.这就是我得到的。

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);

代替此代码:

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

试试这个代码:

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