我在尝试以编程方式创建Cardview时遇到了相同的问题,奇怪的是,看着文档https://developer.android.com/reference/android/support/v7/widget/CardView.html#setCardBackgroundColor%28int %29,Google家伙公开了api来更改名片视图的背景颜色,但是很奇怪,我没有在支持库中成功访问它,所以这对我有用:
CardViewBuilder.java
mBaseLayout = new FrameLayout(context);
// FrameLayout Params
FrameLayout.LayoutParams baseLayoutParams = new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.WRAP_CONTENT);
mBaseLayout.setLayoutParams(baseLayoutParams);
// Create the card view.
mCardview = new CardView(context);
mCardview.setCardElevation(4f);
mCardview.setRadius(8f);
mCardview.setPreventCornerOverlap(true); // The default value for that attribute is by default TRUE, but i reset it to true to make it clear for you guys
CardView.LayoutParams cardLayoutParams = new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.WRAP_CONTENT);
cardLayoutParams.setMargins(12, 0, 12, 0);
mCardview.setLayoutParams(cardLayoutParams);
// Add the card view to the BaseLayout
mBaseLayout.addView(mCardview);
// Create a child view for the cardView that match it's parent size both vertically and horizontally
// Here i create a horizontal linearlayout, you can instantiate the view of your choice
mFilterContainer = new LinearLayout(context);
mFilterContainer.setOrientation(LinearLayout.HORIZONTAL);
mFilterContainer.setPadding(8, 8, 8, 8);
mFilterContainer.setLayoutParams(new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.MATCH_PARENT, Gravity.CENTER));
// And here is the magic to get everything working
// I create a background drawable for this view that have the required background color
// and match the rounded radius of the cardview to have it fit in.
mFilterContainer.setBackgroundResource(R.drawable.filter_container_background);
// Add the horizontal linearlayout to the cardview.
mCardview.addView(mFilterContainer);
filter_container_background.xml
<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle">
<corners android:radius="8dp"/>
<solid android:color="@android:color/white"/>
这样做,我成功地保持了Cardview的阴影和圆角。