Meterial Design常见控件的使用(八):CardVi

2021-01-13  本文已影响0人  bug音音
目录:

CardView简介

public class CardView extends FrameLayout

CardView基本属性(xml文件中)

某些属性使用效果

img

30dp的Elevation(阴影).png

img

ContentPadding为10dp效果 背景为红

img

cardUseCompatPadding_false.png

CardView使用方法

当前IDE:Android Studio 2.2正式版
jdk1.8.102
compileSdkVersion 25
buildToolsVersion "25.0.2"

gradle 导包

dependencies {
    ...
    compile 'com.android.support:cardview-v7:25.2.0'
}

CardView是通常是定义在布局文件中:

<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/activity_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center_vertical|center_horizontal"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.minminaya.cardview_learning.MainActivity">

    <android.support.v7.widget.CardView
        android:id="@+id/w"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        app:cardCornerRadius="10dp"
        app:cardElevation="10dp">

        <ImageView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center"
            android:src="@mipmap/me"/>
    </android.support.v7.widget.CardView>
</RelativeLayout>

通常情况下,只需要radius与elevation就可以达到很漂亮的卡片效果,甚至悬浮式的

当然,也可以在code中使用:

public void setRadius(float radius)
public void setContentPadding
public void setUseCompatPadding(boolean useCompatPadding)
public void setCardBackgroundColor(@ColorInt int color)
...

高级效果 波纹点击(像点击Button那样)

实现方法:

在CardView布局文件节点添加
android:clickable="true"
android:foreground="?android:attr/selectableItemBackground"

gif图录了看不出来就不放图了QAQ

注意 对低版本的兼容处理

CardView在API 21以下,圆角效果会丢失:

<android.support.v7.widget.CardView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        app:cardCornerRadius="25dp" >

        <ImageView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center"
            android:src="@mipmap/me"/>
    </android.support.v7.widget.CardView>

不同安卓版本的效果:

img

Android7.0.png

img

Android4.4.png

解决方法:

cardPreventCornerOverlap官方文档的意思是说在API20及更低版本中添加内边距,其实这个属性是为了防止卡片内容和边角的重叠

加了之后变成了这样:

img

cardPreventCornerOverlap为false

!!!!预警

这和以前竟然不一样了,以前是图片的直角压在了卡片圆角上,而且直角还是在CardView外面,好吧,估计是Android官方优化了一下,现在是卡片效果但是会多出一条白边,啊哈哈哈哈哈啊

大召唤术。。。。借用一张图---------

img

以前的效果

如果遇到这个问题去CardView在API 21以下的圆角效果处理

文末

欢迎关注我的简书,分享Android干货,交流Android技术。
对文章有何见解,或者有何技术问题,都可以在评论区一起留言讨论,我会虔诚为你解答。
最后,如果你想知道更多Android的知识或需要其他资料我这里均免费分享,只需点赞+评论就可以找我获取哦

上一篇下一篇

猜你喜欢

热点阅读