首先介绍以下CardView:是goodle5.0推出得Material Design新特性之中的一种特性。
实现CardView并不难 难的是做适配,CardView是5.0推出的所以5.0以上适配是没有任何问题的但是5.0以下的版本手机就会存在一些问题。如:在5.0以下的手机上是这样的但是在5.0以上版本手机是这样的:
边角是自动帮你裁剪好的。所以你就要自己做一下适配。
布局文件:
<?xml version="1.0" encoding="utf-8"?> <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="match_parent"> <android.support.v7.widget.CardView android:id="@+id/cv1" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginTop="20dp" app:cardBackgroundColor="@color/colorPrimaryDark" app:cardCornerRadius="10dp" app:cardElevation="10dp" app:cardPreventCornerOverlap="false" android:clickable="true" android:foreground="?android:attr/selectableItemBackground" > <tengxyn.com.example.administrator.androidexample.utils.SelectableRoundedImageView android:layout_width="wrap_content" android:layout_height="wrap_content" android:scaleType="centerCrop" android:src="@mipmap/fengjing" app:sriv_left_top_corner_radius="10dp" app:sriv_left_bottom_corner_radius="10dp" app:sriv_right_top_corner_radius="10dp" app:sriv_right_bottom_corner_radius="10dp" /> </android.support.v7.widget.CardView> </LinearLayout>
其中实现点击出现水波纹效果只要加两个属性:
app:cardPreventCornerOverlap="false"
android:clickable="true"
接下来说说图片适配5.0以下问题:
CardView包裹着图片控件但是正常的ImageView但是在5.0以下就会出现第一张图的效果,所以就得自定义ImageView了。
工具类链接:https://download.csdn.net/download/xige1995/10741692
然后把工具类加入项目中之后再在:value文件夹中的styles中加入:
<!--CradView的适配样式--> <declare-styleable name="SelectableRoundedImageView"> <attr name="sriv_left_top_corner_radius" format="dimension"/> <attr name="sriv_right_top_corner_radius" format="dimension"/> <attr name="sriv_left_bottom_corner_radius" format="dimension"/> <attr name="sriv_right_bottom_corner_radius" format="dimension"/> <attr name="sriv_border_width" format="dimension"/> <attr name="sriv_border_color" format="color"/> <attr name="sriv_oval" format="boolean"/> <attr name="android:scaleType"/> </declare-styleable>
就可以了。