Programlı bir şekilde bir kart görünümü oluşturmaya çalışırken aynı sorunla karşılaştım, tuhaf olan https://developer.android.com/reference/android/support/v7/widget/CardView.html#setCardBackgroundColor%28int belgesine bakmak. % 29 , Google adamları bir kart görünümünün arka plan rengini değiştirmek için API'yi kamuoyuna açıkladı, ancak tuhaf bir şekilde, destek kitaplığında ona erişmeyi başaramadım, işte benim için işe yarayan şey:
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"/>
Bunu yaparak, kart görünüm gölgesini ve yuvarlak köşeleri korumayı başarıyorum.