如何通过编程设置Cardview高度?

时间:2018-08-29 08:02:22

标签: android layoutparams cardview

我是android开发的新手,我已经搜索了这个问题,但没有任何解决方案。我想问一下如何将cardviewrecyclerview在一个屏幕中分成三部分吗?

example

这是我的XML

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="1dp"
android:orientation="vertical">

<android.support.v7.widget.CardView
    android:layout_width="match_parent"
    android:id="@+id/card"
    android:layout_height="250dp"
    app:cardCornerRadius="4dp"
    app:cardElevation="1dp"
    app:cardMaxElevation="2dp">

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <com.github.siyamed.shapeimageview.RoundedImageView
            android:id="@+id/image_view"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_alignParentStart="true"
            android:layout_alignParentTop="true"
            android:scaleType="centerCrop"
            android:src="@drawable/ic_launcher_background" />

    </RelativeLayout>
</android.support.v7.widget.CardView>
</LinearLayout>

这是我在“活动”中尝试的代码

View rootLayout = findViewById(R.id.root_layout);
    double height =rootLayout.getLayoutParams().height/3.0;
    CardView card= (CardView)findViewById(R.id.card);
    CardView.LayoutParams layoutParams= (CardView.LayoutParams) card.getLayoutParams();
    layoutParams.height=(int)height;
    layoutParams.width=MATCH_PARENT;

谢谢。

2 个答案:

答案 0 :(得分:0)

尝试获取窗口的高度并将其除以3,

DisplayMetrics displayMetrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
int height = displayMetrics.heightPixels/3;
CardView card= (CardView)findViewById(R.id.card);
LinearLayout.LayoutParams layoutParams= (LinearLayout.LayoutParams) card.getLayoutParams();
layoutParams.height= height;
layoutParams.width=MATCH_PARENT;
card.setLayoutParams(layoutParams);

答案 1 :(得分:0)

就像@ V-rund建议的那样 获取屏幕/窗口的高度并将其除以3,

DisplayMetrics displayMetrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
int height = displayMetrics.heightPixels/3;
CardView card = (CardView)findViewById(R.id.card);

但不使用CardView.LayoutParams来使用LayoutParams作为CardView的父级布局,在您的情况下为LinearLayout

LinearLayout.LayoutParams layoutParams= (LinearLayout.LayoutParams) 
card.getLayoutParams();
layoutParams.height = height;
layoutParams.width = ViewGroup.LayoutParams.MATCH_PARENT;
card.setLayoutParams(layoutParams);

我希望这有助于解决您的问题。