Material Card
卡片是一种控件,可能包含照片,文字和关于单个主题的链接。 它们可能会显示包含不同大小元素的内容,例如带有可变长度字幕的照片。
MaterialCardView是一个基于Android支持库中的CardView的可自定义组件。 MaterialCardView提供了CardView的所有功能,但增加了一些自定义属性,使用起来更加方便实用。
注意:MaterialCardView是Google一个正在进行的实现,还将继续开发新功能和更新。 这些更新中的大多数将基于样式,并具有用于布局内容的内容的附加选项(例如:分隔符,图像,动作和文本处理)。 更新还将包括卡组中卡行为的功能。
用法
要使用MaterialCardView需要引入控件库:
implementation 'com.google.android.material:material:1.1.0-alpha10'
这样你可以使用不止MaterialCardView在内的其他material控件。
在使用前你还需要修改你的AppTheme为Theme.MaterialComponents或者他的子类,否则会报错:
Error inflating class com.google.android.material.card.MaterialCardView
...
...
Caused by: java.lang.IllegalArgumentException: The style on this component requires your app theme to be Theme.MaterialComponents (or a descendant).
如果你的清单文件(AndroidManifest.xml)里面application下是android:theme="@style/AppTheme"
,那么在style.xml里面修改即可:
<style name="AppTheme" parent="Theme.MaterialComponents.Light.NoActionBar">
<!-- Customize your theme here. -->
<item name="colorPrimary">@color/colorPrimary</item>
<item name="colorPrimaryDark">@color/colorPrimaryDark</item>
<item name="colorAccent">@color/colorAccent</item>
</style>
做完前面的操作,你就可以在布局文件中添加MaterialCardView
<com.google.android.material.card.MaterialCardView
android:id="@+id/materialCardView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="16dp"
android:layout_marginRight="16dp"
android:layout_marginTop="16dp"
app:cardElevation="8dp"
app:rippleColor="@color/blue"
app:state_dragged="true"
app:checkedIcon="@drawable/ic_temp"
android:clickable="true">
<TextView
android:id="@+id/text_home"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textAlignment="center"
android:textSize="20sp"
android:text="HomePage"
android:layout_margin="16dp"/>
</com.google.android.material.card.MaterialCardView>
未选中状态
选中状态
属性
XML 属性
特征 | 相关属性 |
---|---|
Border | app:strokeColor app:strokeWidth |
Checkable | android:checkable |
Checked Icon | app:checkedIcon app:checkedIconTint |
Foreground Color | app:cardForegroundColor |
Ripple Color | app:rippleColor |
当然你还可以在Java/Kotlin代码中使用一些方法:
void setCheckable (boolean checkable)//设置是否可以选择
void setChecked (boolean checked)//选中的状态
void setCheckedIcon (Drawable checkedIcon)//选中图标的样式
void setCheckedIconResource (int id)//选中图标的样式
void setDragged (boolean dragged)//是否可拖动
void setRippleColor (ColorStateList rippleColor)//波纹效果的颜色
void setStrokeColor (int strokeColor)//卡片边的颜色
void setStrokeWidth (int strokeWidth)//卡片边的宽带
void toggle ()//控制checkable的开关